All Projects → benzap → Fif

benzap / Fif

Licence: epl-1.0
Stack-based Programming in Clojure(script)

Programming Languages

clojure
4091 projects
scripting
82 projects
forth
179 projects

Labels

Projects that are alternatives of or similar to Fif

Eden
edn (extensible data notation) encoder/decoder for Elixir
Stars: ✭ 32 (-54.93%)
Mutual labels:  edn
eq
jq, but for EDN.
Stars: ✭ 23 (-67.61%)
Mutual labels:  edn
Fipp
Fast Idiomatic Pretty Printer for Clojure
Stars: ✭ 454 (+539.44%)
Mutual labels:  edn
protean
Evolve your RESTful API's and Web Services
Stars: ✭ 31 (-56.34%)
Mutual labels:  edn
edamame
Configurable EDN/Clojure parser with location metadata
Stars: ✭ 129 (+81.69%)
Mutual labels:  edn
Jet
CLI to transform between JSON, EDN and Transit, powered with a minimal query language.
Stars: ✭ 331 (+366.2%)
Mutual labels:  edn
Honeyeql
HoneyEQL is a Clojure library enables you to query database using the EDN Query Language.
Stars: ✭ 111 (+56.34%)
Mutual labels:  edn
Edn Data
EDN parser and generator that works with plain JS data, with support for TS and node streams
Stars: ✭ 44 (-38.03%)
Mutual labels:  edn
meta-schema
Little DSL to make data processing sane with clojure.spec and spec-tools
Stars: ✭ 25 (-64.79%)
Mutual labels:  edn
Coast
The fullest full stack clojure web framework
Stars: ✭ 442 (+522.54%)
Mutual labels:  edn
rewrite-edn
Utility lib on top of rewrite-clj with common operations to update EDN while preserving whitespace and comments.
Stars: ✭ 65 (-8.45%)
Mutual labels:  edn
cq
Clojure Command-line Data Processor for JSON, YAML, EDN, XML and more
Stars: ✭ 111 (+56.34%)
Mutual labels:  edn
Datalevin
A simple, fast and durable Datalog database
Stars: ✭ 360 (+407.04%)
Mutual labels:  edn
clj-rn
A utility for building ClojureScript-based React Native apps
Stars: ✭ 56 (-21.13%)
Mutual labels:  edn
Nippy
High-performance serialization library for Clojure
Stars: ✭ 838 (+1080.28%)
Mutual labels:  edn
Sente
Realtime web comms for Clojure/Script
Stars: ✭ 1,626 (+2190.14%)
Mutual labels:  edn
Muuntaja
Clojure library for fast http api format negotiation, encoding and decoding.
Stars: ✭ 304 (+328.17%)
Mutual labels:  edn
Cause
An EDN-like CRDT (Causal Tree) for Clojure & ClojureScript that automatically tracks history and resolves conflicts.
Stars: ✭ 68 (-4.23%)
Mutual labels:  edn
Mpedn
EDN I/O library for Objective-C (MacOS and iOS)
Stars: ✭ 28 (-60.56%)
Mutual labels:  edn
Walkable
A Clojure(script) SQL library for building APIs: Datomic® (GraphQL-ish) pull syntax, data driven configuration, dynamic filtering with relations in mind
Stars: ✭ 384 (+440.85%)
Mutual labels:  edn

#+TITLE: fif - Stack-based Programming in Clojure(script) #+AUTHOR: Benjamin Zaporzan #+DATE: 2018-04-04 #+EMAIL: [email protected] #+LANGUAGE: en #+OPTIONS: H:2 num:t toc:t \n:nil ::t |:t ^:t f:t tex:t

[[http://benzaporzan.me/fif-playground/][Try it Online!]]

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

[[https://clojars.org/fif][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.

#+BEGIN_SRC clojure (require '[fif.core :as fif])

(fif/reval "Hello World!" . cr) ;; => '() ;; : 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!) ;; => '() ;; : 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])

#+END_SRC

  • Requirements

    fif requires clojure 1.9+

    This could be relaxed to clojure 1.7 with interest.

  • Installation

    For the latest version, please visit [[https://clojars.org/fif-lang/fif][clojars.org]]

    Leiningen/Boot

    #+BEGIN_SRC clojure

    [fif-lang/fif "1.3.1"]

    #+END_SRC

    Clojure CLI/deps.edn

    #+BEGIN_SRC clojure

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

    #+END_SRC

    Gradle

    #+BEGIN_SRC groovy

    compile 'fif-lang:fif:1.3.1'

    #+END_SRC

    Maven

    #+BEGIN_SRC xml

    fif-lang fif 1.3.1

    #+END_SRC

  • 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.

    #+BEGIN_SRC clojure (fif/reval 1 2) ;; => '(1 2) (fif/reval 1 2 +) ;; => '(3) #+END_SRC

    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.

    #+BEGIN_SRC clojure ;; 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)
    

    #+END_SRC

** 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.

#+BEGIN_SRC clojure

(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")

#+END_SRC

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

** Printing to Standard Output

fif maintains a few operators for displaying to standard output.

#+BEGIN_SRC clojure

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

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

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

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

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

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

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

#+END_SRC

** Basic Arithmetic and Stack Manipulation

Note that these examples are similar to [[https://learnxinyminutes.com/docs/forth/][Learn Forth in Y Minutes]]

#+BEGIN_SRC clojure

;; ;; 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)

#+END_SRC

** 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?

#+BEGIN_SRC clojure

(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)

#+END_SRC

The only conditional structures within fif are:

if then

if else then

Examples:

#+BEGIN_SRC clojure

;; 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")

#+END_SRC

** Creating Functions

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

fn <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:

#+BEGIN_SRC clojure

(fif/reval

fn square dup * endfn

5 square) ;; => (25)

(fif/reval

fn add2 2 + endfn
fn add4 add2 add2 endfn

4 add4) ;; => '(8)

#+END_SRC

** Loops

There are currently four standard loops in fif:

do loop

do +loop

begin until

begin while repeat

Examples:

#+BEGIN_SRC clojure

;; 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)

#+END_SRC

** 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.

#+BEGIN_SRC clojure

 ;; 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)

#+END_SRC

** 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 )> reduce

<fn ( item -- 'item )> map

<fn ( item -- boolean )> filter

#+BEGIN_SRC clojure

(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))

#+END_SRC

*** 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.

#+BEGIN_SRC clojure

(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))

#+END_SRC

** 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

#+BEGIN_SRC clojure

(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)
)

#+END_SRC

** 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:

#+BEGIN_SRC clojure

(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!

#+END_SRC

  • 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.

** 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.

#+BEGIN_SRC clojure

(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"}]

#+END_SRC

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:

#+BEGIN_SRC clojure (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"])

#+END_SRC

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.

** 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.

#+BEGIN_SRC clojure (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!)

#+END_SRC

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.

** 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

#+BEGIN_SRC clojure

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

(defn boiling-point-c [] 100)

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

#+END_SRC

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.

#+BEGIN_SRC clojure

(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) ;; : The pill on the top of the stack is: :blue

#+END_SRC

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.

#+BEGIN_SRC clojure

(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)) ;; : The secret message is: The Cake is a Lie ;; :

#+END_SRC

** 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:

#+BEGIN_SRC

(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}

#+END_SRC

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.

#+BEGIN_SRC clojure (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}

#+END_SRC

** 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.

#+BEGIN_SRC clojure

(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))

#+END_SRC

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/
  • 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 --

  • 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 [[http://www.graalvm.org][GraalVM]] with the native-image commandline-tool.

    To generate this executable yourself:

    • clone this repository
    • make sure you have [[https://leiningen.org][leiningen]] installed
    • download and unpack a copy of [[https://github.com/oracle/graal/releases][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.

    #+BEGIN_SRC sh

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

    Usage: fif [options] fif [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!

    #+END_SRC

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

    #+BEGIN_SRC sh

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

    #+END_SRC

    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

    #+BEGIN_SRC clojure

#!/usr/bin/env fif

def help-message "clj dependency tool

Usage: clj-deps add clj-deps remove 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

#+END_SRC

An example of it's use:

#+BEGIN_SRC sh

$ 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 clj-deps remove clj-deps list

Example: clj-deps add fif 1.0.2

#+END_SRC

  • 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.

  • 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
  • Related Readings

    • [[https://www.forth.com/starting-forth/][Starting Forth - Online Book]]
    • [[https://nakkaya.com/2010/12/02/a-simple-forth-interpreter-in-clojure/][A Simple Forth Interpreter in Clojure - Blog Post]]
    • [[https://learnxinyminutes.com/docs/forth/][Learn Forth In Y Minutes]]
    • [[https://github.com/edn-format/edn][Extensible Data Notation - Github Page]]
    • [[https://www.gnu.org/software/gforth/][GForth - Forth Implementation of the GNU Project]]
  • FAQ ** 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 [[https://en.wikipedia.org/wiki/Forth_(programming_language)][the wiki page]] for an interesting read.

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

** 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.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].