Skip to content

Instantly share code, notes, and snippets.

@jwhitlock
Created February 28, 2017 15:03
Show Gist options
  • Save jwhitlock/746b93437e2322c46b0fb1a0db40f255 to your computer and use it in GitHub Desktop.
Save jwhitlock/746b93437e2322c46b0fb1a0db40f255 to your computer and use it in GitHub Desktop.
Code for parsimonious issue #110
from parsimonious import Grammar, NodeVisitor
from parsimonious.grammar import RuleVisitor
class FoamConfigFileParser(NodeVisitor):
"""docstring for FoamConfigFileParser."""
grammar = Grammar(
r"""
body = spacing declaration_list spacing
declaration_list = ( spacing ( declaration / struct )? )*
declaration = identifier spacing value ";"
struct = identifier spacing "{" declaration_list* "}"
identifier = ~"[a-zA-Z]+"
value = text / number
spacing = ( comment / EndOfLine / Space )*
Space = ~"[ \t]*"
EndOfLine = ~"[\n\r]"
comment = ~"(/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*+/)|(//([^\r\n])*)"
number = ~"([-]?[0-9]*)(([.][0-9]+)|([e][+-][0-9]+))?"
text = ~"[a-zA-Z_]+"
""")
def __init__(self):
super(FoamConfigFileParser, self).__init__()
def visit_body(self, node, visited_children):
print "the body"
def visit_identifier(self, node, visited_children):
print "This is the identifier ", node.text
def visit_spacing(self, node, visited_children):
print "Found spacing token"
def visit_comment(self, node, visited_children):
pass
def parse(self, text):
tree = self.grammar.parse(text)
#print tree
FoamConfigFileParser().visit(tree)
#programFile = open("program.foam")
parser = FoamConfigFileParser()
#parser.parse(programFile.read())
parser.parse("""/*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | foam-extend: Open Source CFD |
| \\ / O peration | Version: 3.0 |
| \\ / A nd | Web: http://www.extend-project.de |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class dictionary;
object fvSolution;
}""")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment