Hi there!

I need to wite a parser. I tried to do it using the pegs module. I wrote my 
grammar and it works, it recognizez strings. But now I need to write some 
actions to actually build a syntactic tree while parsing. I need to access the 
captured portions while parsing. Something like:
    
    
    import strutils, pegs
    
    let grammar = peg """
      terms <- ^ term+ $
      term <- \letter* {\d+} \n+
    """
    
    let example = """a1
    b2
    c3
    """
    
    let parseExample = grammar.eventParser:
        pkNonTerminal:
          enter: # p, s, start
            if p.nt.name=="term":
              echo "  It seems like a new term, let's check it..."
          leave: # p, s, start, length (length = -1 in case of failure)
            if p.nt.name=="term" and length >= 1:
              echo "Yes indeed, it's a term and I captured this: '", $1, "'"
    
    let pLen = parseExample(example)
    echo pLen
    
    
    Run

The result is:
    
    
      It seems like a new term, let's check it...
    Yes indeed, it's a term and I captured this: '1'
      It seems like a new term, let's check it...
    Yes indeed, it's a term and I captured this: '1'
      It seems like a new term, let's check it...
    Yes indeed, it's a term and I captured this: '1'
      It seems like a new term, let's check it...
    9
    
    
    Run

Obviously, $1 is not understood as "the first captured string", but as the 
string representation of a literal 1.

How can I access the captured strings for use in the enter/leave procs?

PS: Maybe I'm doing it wrong. I intend to use the whole grammar (about 20-30 
rules) to parse a file in one shot. Is this approach OK?

Reply via email to