ANTLR v3 for Python (1/1)

First Example

The full example is available from our Codeplex repository at ANTLR/v3/Python/Grammar1.

File: ANTLR/v3/Python/Grammar1/Grammar1.g

grammar Grammar1;
options {
  language = Python;
}

greeting: KEYWORD;

KEYWORD: 'HelloWorld';

File: ANTLR/v3/Python/Grammar1/main.py

import antlr3
from Grammar1Lexer import Grammar1Lexer
from Grammar1Parser import Grammar1Parser

def parse(input):
    char_stream = antlr3.ANTLRStringStream(input)
    lexer = Grammar1Lexer(char_stream)
    tokens = antlr3.CommonTokenStream(lexer)
    parser = Grammar1Parser(tokens)
    parser.greeting()

print 'Parsing HelloWorld...'
parse('HelloWorld')

print ''
print 'Parsing world...'
parse('world')

hkjh

C:\...\ANTLR\v3\Python\Grammar1>c:\Python27\python.exe main.py
Parsing HelloWorld...

Parsing world...
line 1:0 mismatched character u'w' expecting 'H'
line 1:1 mismatched character u'o' expecting 'H'
line 1:2 mismatched character u'r' expecting 'H'
line 1:3 mismatched character u'l' expecting 'H'
line 1:4 mismatched character u'd' expecting 'H'
line 1:5 missing KEYWORD at '<EOF>'

C:\...\ANTLR\v3\Python\Grammar1>
import antlr3
from Grammar2Lexer import Grammar2Lexer
from Grammar2Parser import Grammar2Parser

def parse(input):
    char_stream = antlr3.ANTLRStringStream(input)
    lexer = Grammar2Lexer(char_stream)
    tokens = antlr3.CommonTokenStream(lexer)
    parser = Grammar2Parser(tokens)
    parser.greeting()

print 'Parsing HelloWorld...'
parse('HelloWorld')

print ''
print 'Parsing world...'
parse('world')
import antlr3
from Grammar3Lexer import Grammar3Lexer
from Grammar3Parser import Grammar3Parser

def parse(input):
    char_stream = antlr3.ANTLRStringStream(input)
    lexer = Grammar3Lexer(char_stream)
    tokens = antlr3.CommonTokenStream(lexer)
    parser = Grammar3Parser(tokens)
    parser.sentence()

print 'Parsing HelloWorld...'
parse('HelloWorld')

print ''
print 'Parsing HowDoYouDo?...'
parse('HowDoYouDo?')

print ''
print 'Parsing world...'
parse('world')

print ''
print 'Parsing Hello...'
parse('Hello')

blog comments powered by Disqus

Copyright(c) 2006-2015 Xavier Leclercq | Privacy policy

Home
Contact Us
Search