项目作者: adrianton3

项目描述 :
S-expression parser and macro expander
高级语言: JavaScript
项目地址: git://github.com/adrianton3/espace.git
创建时间: 2014-03-27T06:37:20Z
项目社区:https://github.com/adrianton3/espace

开源协议:MIT License

下载


espace

S-expression parser in JavaScript

Tokenizer

  1. const options = {
  2. whitespace: false,
  3. comments: false,
  4. coords: true,
  5. prefixes: {
  6. '#': 'map',
  7. },
  8. }
  9. const source = '(fun (a b) (+ a b))'
  10. const tokens = espace.Tokenizer.tokenize(source, options) //

Parser

  1. const source = '(fun (a b) (+ a b))'
  2. const tokens = espace.Tokenizer.tokenize(source)
  3. const tree = espace.Parser.parse(tokens) //

Macro expander

  1. const source = '(+ a b c)'
  2. const pattern = '(+ x y z)'
  3. const replace = '(+ (+ x y) z)'
  4. const parse = (source) =>
  5. espace.Parser.parse(espace.Tokenizer.tokenize(source))
  6. const sourceTree = parse(source)
  7. const patternTree = parse(pattern)
  8. const replaceTree = parse(replace)
  9. espace.Expander.expand(sourceTree, patternTree, replaceTree) //

Pattern can have more than one level:

  • can replace all subexpressions of the form (- (- x y)) with (- y x)

Pattern supports rest variables:

  • can replace all (first (list x y...)) with (list y...)
  • can replace all (last (list x... y)) with (list x...)

Variables prefixed by _ in replace get uniquely named:

  • can replace all (swap x y) with (let (_tmp x) (set! x y) (set! y _tmp))