Created
August 15, 2012 07:09
-
-
Save dahu/3357301 to your computer and use it in GitHub Desktop.
Ye Olde VimPEG
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| " Introducing Vimpeg - A PEG Parser Generator for Vim | |
| " Barry Arthur, 01 Oct 2011 | |
| " Evaluate a series of inline integer addition & subtraction operations | |
| let p = vimpeg#parser({'skip_white': 1}) | |
| call p.e('\d\+', {'id': 'integer'}) | |
| let addsub = | |
| \ p.and( | |
| \ [ 'integer', | |
| \ p.maybe_many( | |
| \ p.and( | |
| \ [ p.or( | |
| \ [ p.e('+'), | |
| \ p.e('-')]), | |
| \ 'integer'])), | |
| \ p.e('$')], | |
| \ {'on_match': 'AddSub'}) | |
| function! AddSub(args) | |
| let val = remove(a:args, 0) | |
| let args = a:args[0] | |
| while len(args) > 0 | |
| let pair = remove(args, 0) | |
| let val = (pair[0] == '+') ? (val + pair[1]) : (val - pair[1]) | |
| endwhile | |
| return val | |
| endfunction | |
| function! EvaluateExpression(str) | |
| let res = g:addsub.match(a:str) | |
| if res.is_matched | |
| return res.value | |
| else | |
| return res.errmsg | |
| endif | |
| endfunction | |
| echo EvaluateExpression('123') | |
| echo EvaluateExpression('1 + 2') | |
| echo EvaluateExpression('1 + 2 + 3') | |
| echo EvaluateExpression('4 - 5 + 6') | |
| echo EvaluateExpression('1 - a') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment