• Print

Author Topic: Does anyone Know How to Convert Python to QB64? or and QB64 to Python?  (Read 81 times)

HACKER

  • Limited Member
  • Hero Member
  • *
  • Posts: 761
    • Email
Does anyone Know How to Convert Python to QB64? or and QB64 to Python?
« on: October 11, 2012, 01:37:51 AM »
Hi...

Does anyone Know How to Convert Python to QB64? or and QB64 to Python?

I found this Program Below! (BAS to Python) But I'm Scratching My Head on how to Get it to Work!?

And as to whether it will Work with Qb64 Programs? or Just Basic BASIC ?


Code: [Select]
import re

def tokenise(f):
    pat = [(r"""("[^"]*")""", "str"),
           ("'.*$", "comment"),
           (r"(\d+(\.\d+)?)|(\.\d+)", "num"),
           ("\+","plus"),
           ("-","minus"),
           ("\*","times"),
           ("/","divide"),
           ("\^","pow"),
           ("\(","lp"),
           ("\)", "rp"),
           ("=", "assign"),
           (":", "colon"),
           (";", "semicolon"),
           (",", "comma"),
           ("PRINT","print"),
           ("DATA","data"),
           ("FOR","for"),
           ("TO","to"),
           ("NEXT","next"),
           ("READ","read"),
           ("INT","int"),
           ("PI|COS|SIN|ATN|EXP","math"),
           ("[A-Z]+","identifier"),
           ]
    for l in f:
        x = re.match("([0-9]+) (.*)", l)
        if x:
            print l
            linenum,line = x.groups()
            result = ""
            s = line
            while s:
                s = s.lstrip()
                for p,id in pat:
                    x = re.match(p, s)
                    if x:
                        #print (id, s[:x.span()[1]])
                        yield (id, s[:x.span()[1]])
                        s = s[x.span()[1]:]
                        break
            yield ("eol", "\n")

class lookahead:
    def __init__(self, tok):
        self.tok = tok
        self.n = self.tok.next()
        self.done = False
    def look(self):
        return self.n
    def next(self):
        try:
            self.n = self.tok.next()
        except StopIteration:
            self.done = True
        return self.n


variable_renaming = {"DS":"store_diameter",
                     "HS":"store_height",
                     "AS":"store_surface_area",
                     "ND":"n_days",
                     "DUSE":"DHW_use",
                     "PP":"pump_power",
                     "FP":"fan_power"
                     }


def do_identifier(tok):
    id,s = tok.look()
    #if variable_renaming.has_key(s):
    #    return variable_renaming[s]
    #else:
    iden = s.capitalize()
    return iden

def do_value(tok):
    result = ""
    while not tok.look()[0] == "eol":
        id,s = tok.look()
        if id == "semicolon" or id == "comment" or id == "colon" or id == "comma":
            break
        if id == "identifier":
            result += do_identifier(tok)
        elif id == "math":
            result += "math."+s.lower()
        elif id == "int":
            result += "int"
        elif id == "pow":
            result += "**"
        elif id == "num":
            result += str(float(s))
        else:
            result += s
        id,s = tok.next()
    return result

def do_assign(tok):
    result = do_identifier(tok)
    tok.next()
    assert(tok.look()[0] == "assign")
    tok.next()
    return result + " = " + do_value(tok)

def do_for(tok):
    assert(tok.look()[0] == "for")
    tok.next()
   
    loop_var = do_identifier(tok)
    tok.next()
    assert(tok.look()[0] == "assign")
    tok.next()
    st = int(tok.look()[1])
    assert(tok.look()[0] == "num")
    tok.next()
    assert(tok.look()[0] == "to")
    tok.next()
    end = int(tok.look()[1])
    assert(tok.look()[0] == "num")
    tok.next()
    result = "for %s in range(%d, %d):" % (loop_var, st, end+1)
    while not tok.done:
        result += "    " + do_command(tok, "next") + "\n"
        if tok.look()[0] == "next":
            tok.next()
            break
        assert(tok.look()[0] == 'eol')
        tok.next()
    print tok.look()
    out_var = do_identifier(tok)
    tok.next()
    assert(out_var == loop_var)
    return result



def do_data(tok):
    assert(tok.look()[0] == "data")
    tok.next()
    data = [] # data for DATA and READ commands
    while not tok.look()[0] == "eol":
        data.append(float(tok.look()[1]))
        assert(tok.look()[0] == "num")
        tok.next()
        if tok.look()[0] == "eol": break
        assert(tok.look()[0] == "comma")
        tok.next()
    return "data = %s" % str(data)

def do_read(tok):
    assert(tok.look()[0] == "read")
    tok.next()
   
    loop_var = do_identifier(tok)
    tok.next()
    result = "%s = data[0]; del data[0]\n" % (loop_var)
    return result


comment_margin = 50
page_margin = 120

def do_command(tok, breakon=None):
    result = ""
    while not tok.look()[0] == "eol":
        id,s = tok.look()
        if breakon and id == breakon: return result
        if id == "print":
            result += "print "
            tok.next()
            first = True
            while not tok.look()[0] == "eol":
                id,s = tok.look()
                print id,s
                if id == "semicolon":
                    result += ", "
                    tok.next()
                if id == "comma":
                    result += ", "
                    tok.next()
                elif id == "str":
                    if first:
                        x = re.match("\"\d+'(.*)\"$", s)
                        print x
                        if x:
                            s = '"%s"' % x.groups()[0]
                        print s
                    result += s
                    tok.next()
                else:
                    result += do_value(tok)
                first = False
        elif id == "data":
            result += do_data(tok)
        elif id == "read":
            result += do_read(tok)
        elif id == "for":
            result += do_for(tok)
        elif id == "next":
            assert(0)
        elif id == "identifier":
            result += do_assign(tok)
        elif id == "colon":
            tok.next()
            result += "\n"
        elif id == "comment":
            tok.next()
           
            trresult = result+" "*(max(1,comment_margin-len(result.split('\n')[-1])))+"# " + s
            if result.strip() == '':
                result += "# " + s
            elif len(trresult) >= page_margin:
                result += "\n# " + s
            else:
                result = trresult
        else:
            print id, s
    return result

def do_code(tok):
    while not tok.done:
        yield do_command(tok)
        assert(tok.look()[0] == 'eol')
        tok.next()

src_name = "nick3"
import sys
if len(sys.argv) > 1:
    src_name = sys.argv[1]
f = open('%s.bas' % src_name, "r")
target = open("%s.py" % src_name, "w")
target.write("""import math\n""")

tok = lookahead(tokenise(f))
       
target.write('\n'.join( x + "\n" for x in do_code(tok)))


  • Print