def parse(fname, lexonly): import pyggy l, ltab = pyggy.getlexer("ansic.pyl") p, ptab = pyggy.getparser("ansic.pyg") p.setlexer(l) l.setinput(preprocess(fname)) if lexonly: while 1: tok = l.token() if tok is None: break print tok, l.value if tok == "#ERR#": print "error at %s:%d" % (lextab.fname, lextab.lineno) break else: # parse the input tree = p.parse() if tree == None: print "error at %s:%d near %s" % (lextab.fname, lextab.lineno, l.value) else: print "displaying tree" #print tree #pyggy.glr.dottree(tree) t = pyggy.proctree(tree, ptab) pprint.pprint(t) print "done"
def parse(fname, lexonly): import pyggy l, ltab = pyggy.getlexer("ansic.pyl") p, ptab = pyggy.getparser("ansic.pyg") p.setlexer(l) l.setinput(preprocess(fname)) if lexonly: while 1: tok = l.token() if tok is None: break print tok, l.value if tok == "#ERR#": print "error at %s:%d" % (lextab.fname, lextab.lineno) break else: # parse the input tree = p.parse() if tree == None: print "error at %s:%d near %s" % (lextab.fname, lextab.lineno, l.value) else: print "displaying tree" # print tree # pyggy.glr.dottree(tree) t = pyggy.proctree(tree, ptab) pprint.pprint(t) print "done"
def clean(self,value): value = value.replace(r'\n','\n') l,ltab = pyggy.getlexer("badge.pyl") parser,ptab = pyggy.getparser("badge.pyg") l.setinputstr(value) parser.setlexer(l) try: parser.parse() except Exception: raise forms.ValidationError("Must be a valid config string") return value
def build_badge(badge): #pyggy uses a hackish way of loading the generated lexer. #and the .pyl and .pyg seem to have to be in the current directory bgGens = {'gradient':buildGradient,'transparent':buildTransparent} startDir = os.getcwd() os.chdir(settings.SITE_ROOT) r = settings.SITE_ROOT l,ltab= pyggy.getlexer("badge.pyl") parser,ptab = pyggy.getparser("badge.pyg") if badge.is_custom: fmt = buildFormatFromTemplate(badge) else: fmt = badge.format l.setinputstr(fmt) while True: x = l.token() if x is None: break print x,l.value l.setinputstr(fmt) parser.setlexer(l) tree = parser.parse() os.chdir(startDir) sstat = lambda stat:sumStat(badge.user,badge.players,stat) fields = {'WINS':sstat('wins'),'LOSSES':sstat('losses'),'TOTAL':sstat('played'),'MODERATED':sstat('modded'),'NAME':badge.user.username,'PMODERATED':sstat('totalPlayersModded')} badgeData = buildBadgeData(tree,fields) lines = badgeData['lines'] sizes = [sizeLine(line) for line in lines] zsizes = zip(*sizes) width = 2*HBORDER + max(zsizes[0]) height = LINE_SPACE + sum((LINE_SPACE + h for h in zsizes[1])) base = Image.open(settings.MEDIA_ROOT + "/images/badgeBase.png").resize((width,height)) mask = Image.open(settings.MEDIA_ROOT + "/images/badgeMask.png").resize((width,height),Image.ANTIALIAS) img = bgGens[badgeData['background']]((width,height),badgeData['colors']) # img = Image.new("RGB",(width,height)) # img.putalpha(0) # img.paste(base,(0,0,width,height),mask) d = ImageDraw.Draw(img) cur_y = LINE_SPACE for line,size in zip(lines,sizes): cur_x = HBORDER for text,font,color in line: entry_size = font.getsize(text) line_offset = size[1] - entry_size[1] d.text((cur_x,cur_y+line_offset),text,font=font,fill=color) cur_x+=entry_size[0] cur_y+=size[1]+LINE_SPACE img.save(settings.MEDIA_ROOT +"/"+ badge.url)
def clean_config(self): if (('config' in self.cleaned_data) and (self.cleaned_data['config'])): value = self.cleaned_data['config'] value = value.replace(r'\n','\n') if(value[-1]!="\n"):#grammar requires a newline at end value = value+"\n" startDir = os.getcwd() os.chdir(settings.SITE_ROOT) l,ltab = pyggy.getlexer("badge.pyl") parser,ptab = pyggy.getparser("badge.pyg") l.setinputstr(value) parser.setlexer(l) os.chdir(startDir) try: parser.parse() except Exception: raise forms.ValidationError("Must be a valid config string") return value
#!/usr/bin/python import pyggy l,tab = pyggy.getlexer("test1.pyl") l.setinput("-") while 1 : x = l.token() if x is None : break print x, l.value
return kids[0].sym[1] else: return "(%s %s %s)" % (exprstr( kids[0]), kids[1].sym[1], exprstr(kids[2])) def exprstr(e): res = [] for p in e.possibilities: res.append(singleexprstr(p.elements)) if len(res) == 1: return res[0] else: return "[%s]" % " or ".join(res) # instantiate the lexer and parser l, ltab = pyggy.getlexer("test2.pyl") p, ptab = pyggy.getparser("test2.pyg") l.setinput("-") p.setlexer(l) # parse the input tree = p.parse() if tree == None: print "error!" else: print "parse done: ", exprstr(tree) # if you have dot, try uncommenting the following #pyggy.glr.dottree(tree)
#!/usr/bin/python import pyggy l, tab = pyggy.getlexer("test1.pyl") l.setinput("-") while 1: x = l.token() if x is None: break print x, l.value
""" pgy_calc.py A simple calculator with variables based on calc.py from the PLY web page. """ import sys import pyggy # build the lexer and parser l,ltab = pyggy.getlexer("pyg_calc.pyl") p,ptab = pyggy.getparser("pyg_calc.pyg") p.setlexer(l) while 1: sys.stdout.write("calc > ") line = sys.stdin.readline() if line == "" : break l.setinputstr(line) try : tree = p.parse() except pyggy.ParseError,e : print "parse error at '%s'" % e.str continue pyggy.proctree(tree, ptab)
# ----------------------------------------------------------------------------- # ply_calc.py # # A simple calculator with variables -- using pylly lexer # # derived from calc.py from the PLY web page. # example of using a PyLly lexer with PLY. # ----------------------------------------------------------------------------- import sys # build the lexer import pyggy l,lexer = pyggy.getlexer("ply_calc.pyl") tokens = lexer.tokens # Parsing rules precedence = ( ('left','PLUS','MINUS'), ('left','TIMES','DIVIDE'), ('right','UMINUS'), ) # dictionary of names names = { } def p_statement_assign(t): 'statement : NAME EQUALS expression' names[t[1]] = t[3]
} } .field public static valuetype CharArray8 Format at FormatData //----------- Data declaration .data FormatData = bytearray(25 64 00 00 00 00 00 00) // d . . . . . . //----------- Value type as placeholder .class public explicit CharArray8 extends [mscorlib]System.ValueType { .size 8 } //----------- Calling unmanaged code .method public static pinvokeimpl("msvcrt.dll" cdecl) vararg int32 sscanf(string,int8*) cil managed { } """ # build the lexer and parser l,ltab = pyggy.getlexer("mpython_lex.pyl") # # A instancia da especificacao gramatical onde fica todas as acoes eh 'ptab' # p,ptab = pyggy.getparser("mpython_grm.pyg") p.setlexer(l) def usage(n): print MODO_USO % n sys.exit(0) def gerar_codigo(nomeArqEntrada): l.setinput(nomeArqEntrada) tree = None try: tree = p.parse()
# ----------------------------------------------------------------------------- # ply_calc.py # # A simple calculator with variables -- using pylly lexer # # derived from calc.py from the PLY web page. # example of using a PyLly lexer with PLY. # ----------------------------------------------------------------------------- import sys # build the lexer import pyggy l, lexer = pyggy.getlexer("ply_calc.pyl") tokens = lexer.tokens # Parsing rules precedence = ( ('left', 'PLUS', 'MINUS'), ('left', 'TIMES', 'DIVIDE'), ('right', 'UMINUS'), ) # dictionary of names names = {} def p_statement_assign(t): 'statement : NAME EQUALS expression' names[t[1]] = t[3]
def singleexprstr(kids) : if len(kids) == 1 : return kids[0].sym[1] else : return "(%s %s %s)" % (exprstr(kids[0]), kids[1].sym[1], exprstr(kids[2])) def exprstr(e) : res = [] for p in e.possibilities : res.append(singleexprstr(p.elements)) if len(res) == 1 : return res[0] else : return "[%s]" % " or ".join(res) # instantiate the lexer and parser l,ltab = pyggy.getlexer("test2.pyl") p,ptab = pyggy.getparser("test2.pyg") l.setinput("-") p.setlexer(l) # parse the input tree = p.parse() if tree == None : print "error!" else : print "parse done: ", exprstr(tree) # if you have dot, try uncommenting the following #pyggy.glr.dottree(tree)