martes, 25 de octubre de 2016

Ruby and the Interpreter Pattern

This week article was about SIF (S-Expression interpreter Framework) developed by Ariel Ortiz. This program teaches how is a programming language construct (in a tree form) and then compiled, this code is built in Ruby following the interpreter pattern.

S-expressions (symbolic expressions) are a parenthesized prefix notation, mainly used in the Lisp family languages. The interpreter pattern is one of the classical Gang of Four (GoF) behavioral patterns. A program is portrayed as a tree in which every construct or element in the source program is represented by a specific kind of node. Every node responds to a special operation called interpret, which is responsible for performing the expected behavior associated with the corresponding language element. The interpret operation receives a context as a parameter, which is basically a symbol table where variable bindings can be established and queried during runtime. The framework’s job begins by reading a source program represented as a string. The Ruby regular expression API is used to scan the input, and a hand written recursive descent parser performs the syntactic analysis that transforms the S-expressions into the equivalent Ruby data values. These objects are then traversed in order to construct the tree required by the interpreter pattern.

The Interpreter.eval class method is the heart of the SIF. This method receives a string and a context as inputs. The string should contain one or more valid S-expressions, while the context may be a hash object in which each key represents the name of a variable that’s associated with some specific value. The hash keys are assumed to be Ruby Symbols, and the hash itself should be mutable in order to allow the S-expressions to modify its contents if needed. This method parses the input string converting the Sexpressions into their equivalent Ruby data values, and then proceeds with the evaluation using the interpreter pattern.

The SIF provides a class called Primitives which provides a set of predefined primitive procedures (including operations for arithmetic, list processing, and type predicates) that can be readily used. The class method Primitives.context should be used to get a copy of the context containing the variable bindings to the primitive procedures.
The SIF uses strict evaluation when calling a procedure. This means that all the arguments of a procedure are completely evaluated before being called.

If you are interested in reading this article here's the link: Ruby and the Interpreter Pattern.
If you are interested in downloading SIF here's the link: SIF.

No hay comentarios:

Publicar un comentario