7.12.2006
4:28 AM

EasyParser was my first project with Io. It was initially a port of the magnificient pyparsing library, but as the languages differ, so do the libraries.

Anyway, EasyParser.io is an alternative way to construct grammars and process text. Each element can be used as an insertion point to process tokens and produce objects within a parse tree, so that only a single pass is needed. Here's an example:

fourFn := EasyParser clone do(
    // Parse expressions
    number := charsIn(nums)
    
    +- := literal("+") or literal("-")
    */ := literal("*") or literal("/")
    
    lparen := literal("(") suppress
    rparen := literal(")") suppress

    expr := scout
    
    atom := number or(lparen and(expr) and(rparen))
    
    term := scout
    term is(atom and [(*/) and term])
    
    expr is(term and [(+-) and expr]) ignore(whitespace)

    main := stringStart and(expr) and(stringEnd)

    // Parse actions
    number onParse(tokens at(0) asNumber)
    
    term onParse(
        oper := tokens at(1)
        if(oper == "*",
            tokens at(0) * tokens at(2)
        ,
        if(oper == "/",
            tokens at(0) / tokens at(2)
        ,
            tokens at(0)
        ))
    )
    
    expr onParse(
        oper := tokens at(1)
        if(oper == "+",
            tokens at(0) + tokens at(2)
        ,
        if(oper == "-",
            tokens at(0) - tokens at(2)
        ,
            tokens at(0)
        ))
    )
)

This defines a simple four-function evaluator. Now, we can just:

fourFn parseString("41 + 1") at(0)               //=> 42
fourFn parseString("1 + 2 * (5 - 4) / 2") at(0)  //=> 2
fourFn parseString("10 * (4 + 2)") at(0)         //=> 60

I've set up a darcs repo on my http space over at leafo.net, so get the source at:

darcs get --partial http://paragon.leafo.net/easyparser/

And update with:

darcs pull http://paragon.leafo.net/easyparser/

A quick sidenote: I'm putting up a daily Windows build of Io, straight from darcs, right here. I'm pouring forth all efforts to get IoDesktop and IoServer running, but it's an uphill struggle. I'll update you as we get closer.