code stringlengths 1 1.49M | vector listlengths 0 7.38k | snippet listlengths 0 7.38k |
|---|---|---|
# @mark.steps
# ----------------------------------------------------------------------------
# STEPS:
# ----------------------------------------------------------------------------
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from behave import given, when, then
from hamcrest import assert_that, contains_string
HOME = "http://localhost:4567"
@given('user has been sign out')
def step_user_has_sign_out(context):
context.browser.get(HOME)
try:
logout_link = context.browser.find_element_by_link_text('Logout')
logout_link.click()
except NoSuchElementException:
pass
@when('I go to "{url}"')
def step_go_to(context, url):
context.browser.get(url)
@then('I should see main page html')
def step_see_main_page(context):
guest_name_label = 'Guestbook name:'
page_source = context.browser.page_source
assert_that(page_source, contains_string(guest_name_label))
elm = context.browser.find_element_by_id("submit")
elm.value = "Sign Guestbook"
elm = context.browser.find_element_by_id("switch")
elm.value = "switch"
@when('I sign "{content}"')
def setp_sign_content(context, content):
elm = context.browser.find_element_by_name("content")
elm.send_keys(content)
button = context.browser.find_element_by_id("submit")
button.click()
@when('I login as "{user}"')
def setp_login_as(context, user):
login_link = context.browser.find_element_by_link_text('Login')
login_link.click()
elm = context.browser.find_element_by_name("email")
elm.clear()
elm.send_keys(user)
elm = context.browser.find_element_by_id("submit-login")
elm.click()
wait = WebDriverWait(context.browser, 5)
wait.until(EC.presence_of_element_located((By.NAME, 'content')))
@then('I should see "{content}" signed by "{user}"')
def setp_see_content(context, content, user):
page_source = context.browser.page_source
assert_that(page_source, contains_string("<blockquote>%s</blockquote>" % content))
assert_that(page_source, contains_string(user))
| [
[
1,
0,
0.0746,
0.0149,
0,
0.66,
0,
844,
0,
1,
0,
0,
844,
0,
0
],
[
1,
0,
0.0896,
0.0149,
0,
0.66,
0.0833,
328,
0,
1,
0,
0,
328,
0,
0
],
[
1,
0,
0.1045,
0.0149,
0,
... | [
"from selenium.common.exceptions import NoSuchElementException",
"from selenium.webdriver.common.by import By",
"from selenium.webdriver.support.ui import WebDriverWait",
"from selenium.webdriver.support import expected_conditions as EC",
"from behave import given, when, then",
"from hamcrest import asser... |
import os
import sys
import signal
import subprocess
from selenium import webdriver
def before_all(context):
# NOTE: you can change to whatever driver you want, I use Firefox as a demo
context.browser = webdriver.Firefox()
# start the app engine server
# make sure dev_appserver.py is in your PATH
if os.environ['SERVER_RUNNING'] != "True":
context.app_engine_proc = subprocess.Popen([
'dev_appserver.py',
'--clear_datastore=true',
'--port=4567', "%s/../" %
os.path.dirname(os.path.abspath(__file__))],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
line = context.app_engine_proc.stdout.readline()
count = 75
while ('Starting admin server' not in line) and (count > 0):
sys.stdout.write(line)
sys.stdout.write("count: %d\n" % count)
sys.stdout.flush()
line = context.app_engine_proc.stdout.readline()
count = count - 1
def after_all(context):
context.browser.quit()
if os.environ['SERVER_RUNNING'] != "True":
os.kill(context.app_engine_proc.pid, signal.SIGINT)
| [
[
1,
0,
0.0286,
0.0286,
0,
0.66,
0,
688,
0,
1,
0,
0,
688,
0,
0
],
[
1,
0,
0.0571,
0.0286,
0,
0.66,
0.1667,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.0857,
0.0286,
0,
... | [
"import os",
"import sys",
"import signal",
"import subprocess",
"from selenium import webdriver",
"def before_all(context):\n # NOTE: you can change to whatever driver you want, I use Firefox as a demo\n context.browser = webdriver.Firefox()\n # start the app engine server\n # make sure dev_a... |
#!/usr/bin/env python
import os
import urllib
from google.appengine.api import users
from google.appengine.ext import ndb
import jinja2
import webapp2
JINJA_ENVIRONMENT = jinja2.Environment(
loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),
extensions=['jinja2.ext.autoescape'],
autoescape=True)
DEFAULT_GUESTBOOK_NAME = 'default_guestbook'
# We set a parent key on the 'Greetings' to ensure that they are all in the
# same entity group.
# Queries across the single entity group will be consistent.
# However, the write rate should be limited to ~1/second.
def guestbook_key(guestbook_name=DEFAULT_GUESTBOOK_NAME):
"""
Constructs a Datastore key for a Guestbook entity with guestbook_name.
"""
return ndb.Key('Guestbook', guestbook_name)
# Refactor get url link by user
def get_user_url(uri):
if users.get_current_user():
url = users.create_logout_url(uri)
url_linktext = 'Logout'
else:
url = users.create_login_url(uri)
url_linktext = 'Login'
return {
'url': url,
'url_linktext': url_linktext
}
class Greeting(ndb.Model):
"""
Models an individual Guestbook entry with author, content, and date.
You can create a Greeting:
>>> greeting = Greeting(parent=guestbook_key(), content='test content')
>>> greeting
Greeting(key=Key('Guestbook', 'default_guestbook', 'Greeting', None), content='test content')
>>> created_key = greeting.put()
You can query to select the greeting:
>>> greetings_query = Greeting.query(ancestor=guestbook_key())
>>> list(greetings_query.fetch(10)) # doctest: +ELLIPSIS
[Greeting(key=Key('Guestbook', 'default_guestbook', ...)]
To modify a greeting, change one of its properties and ``put()`` it again.
>>> greeting_2 = _[0]
>>> greeting_2.content = 'test 2'
>>> created_key_2 = greeting_2.put()
>>> greeting_2.content
u'test 2'
Verify that the key for the greeting doesn't change.
>>> bool(created_key == created_key_2)
True
"""
author = ndb.UserProperty()
content = ndb.StringProperty(indexed=False)
date = ndb.DateTimeProperty(auto_now_add=True)
class MainPage(webapp2.RequestHandler):
def get(self):
guestbook_name = self.request.get('guestbook_name',
DEFAULT_GUESTBOOK_NAME)
greetings_query = Greeting.query(
ancestor=guestbook_key(guestbook_name)).order(-Greeting.date)
greetings = greetings_query.fetch(10)
user_url = get_user_url(self.request.uri)
template_values = {
'greetings': greetings,
'guestbook_name': urllib.quote_plus(guestbook_name),
'url': user_url['url'],
'url_linktext': user_url['url_linktext'],
}
template = JINJA_ENVIRONMENT.get_template('index.html')
self.response.write(template.render(template_values))
class Guestbook(webapp2.RequestHandler):
def post(self):
# We set the same parent key on the 'Greeting' to ensure each Greeting
# is in the same entity group. Queries across the single entity group
# will be consistent. However, the write rate to a single entity group
# should be limited to ~1/second.
guestbook_name = self.request.get('guestbook_name',
DEFAULT_GUESTBOOK_NAME)
greeting = Greeting(parent=guestbook_key(guestbook_name))
if users.get_current_user():
greeting.author = users.get_current_user()
greeting.content = self.request.get('content')
greeting.put()
query_params = {'guestbook_name': guestbook_name}
self.redirect('/?' + urllib.urlencode(query_params))
def make_application(debug_to_set=True):
return webapp2.WSGIApplication([
('/', MainPage),
('/sign', Guestbook),
], debug=debug_to_set)
application = make_application(True)
| [
[
1,
0,
0.0159,
0.0079,
0,
0.66,
0,
688,
0,
1,
0,
0,
688,
0,
0
],
[
1,
0,
0.0238,
0.0079,
0,
0.66,
0.0714,
614,
0,
1,
0,
0,
614,
0,
0
],
[
1,
0,
0.0397,
0.0079,
0,
... | [
"import os",
"import urllib",
"from google.appengine.api import users",
"from google.appengine.ext import ndb",
"import jinja2",
"import webapp2",
"JINJA_ENVIRONMENT = jinja2.Environment(\n loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),\n extensions=['jinja2.ext.autoescape'],\n auto... |
__author__ = 'wlee'
import Pycluster
import random
from collections import deque
import numpy
import math
checkins = open('Brightkite_totalCheckins.txt','rb')
kmlstatement=[]
geos=[]
geo_avgs=dict()
id=0
count = 0
valid_ids =[]
write_valid_ids = open('valid_ids2.txt','wb')
us_num = 0
def check_similarity(u):
lats = numpy.zeros(len(u))
longs = numpy.zeros(len(u))
if u!=0:
for i in range(len(u)):
lats[i] = u[i][0]
longs[i] = u[i][1]
similarity_lats = numpy.var(lats)
similarity_longs = numpy.var(longs)
if similarity_lats > 0.5:
return False
if similarity_longs > 0.5:
return False
return True
def calculate_mean(u):
lats = numpy.zeros(len(u))
longs = numpy.zeros(len(u))
if u!=0:
for i in range(len(u)):
lats[i] = u[i][0]
longs[i] = u[i][1]
return numpy.mean(lats),numpy.mean(longs)
def won_cluster(geos):
results =[]
index_queue = deque()
index_queue.append(0)
geo_locations = dict()
geo_locations[0]=geos
while len(index_queue):
current_id=index_queue.pop()
current_items= geo_locations[current_id]
info= Pycluster.kcluster(current_items,2)
index = info[0]
count = 0
left_list = []
right_list =[]
left_count = 0
right_count = 0
for geo_item in current_items:
if index[count] == 0:
left_list.append(geo_item)
left_count +=1
if index[count] == 1:
right_list.append(geo_item)
right_count +=1
count +=1
if check_similarity(left_list) == False:
index_queue.append(2*current_id +1)
geo_locations[2*current_id +1]=left_list
else:
l = calculate_mean(left_list)
results.append([l[0],l[1]])
if check_similarity(right_list) == False:
index_queue.append(2*current_id +2)
geo_locations[2*current_id +2]=right_list
else:
r = calculate_mean(right_list)
results.append([r[0],r[1]])
return results
for checkin in checkins:
parsed_info= checkin.split("\t")
if len(parsed_info)<3:
continue
if str(id) == str(parsed_info[0]):
if len(parsed_info[2])<3:
continue
lat = float(parsed_info[2])
lng = float(parsed_info[3])
if -124< float(lng) and -60>float(lng):
if 17< float(lat) and 49> float(lat):
geo = [parsed_info[2],parsed_info[3]]
geos.append(geo)
else:
lat = float(parsed_info[2])
lng = float(parsed_info[3])
count = 0
num_check = []
temp_geo=[]
if len(geos)>=2:
clustered_groups= won_cluster(geos)
if len(clustered_groups)<5:
for g in clustered_groups:
write_valid_ids.write(str(int(id))+"\t"+str(g[0])+"\t"+str(g[1])+"\n")
#print id,len(clustered_groups)
id = parsed_info[0]
if -124< float(lng) and -60>float(lng):
if 17< float(lat) and 49> float(lat):
geo = [parsed_info[2],parsed_info[3]]
geos = []
geos.append(geo)
print us_num
| [
[
14,
0,
0.0059,
0.0059,
0,
0.66,
0,
777,
1,
0,
0,
0,
0,
3,
0
],
[
1,
0,
0.0118,
0.0059,
0,
0.66,
0.0526,
86,
0,
1,
0,
0,
86,
0,
0
],
[
1,
0,
0.0178,
0.0059,
0,
0.6... | [
"__author__ = 'wlee'",
"import Pycluster",
"import random",
"from collections import deque",
"import numpy",
"import math",
"checkins = open('Brightkite_totalCheckins.txt','rb')",
"kmlstatement=[]",
"geos=[]",
"geo_avgs=dict()",
"id=0",
"count = 0",
"valid_ids =[]",
"write_valid_ids = open... |
'''
Created on Dec 7, 2011
@author: jeongjin
'''
import os
import random
#src_path = "./"
src_path = "/Users/jeongjin/Dropbox/224w/data/AgraphTestData/"
label_path = ""
label_file = None
feature_file_dct = {}
result_size = 500000
result_file_name = src_path+"data_"+str(result_size)+".csv"
for filename in os.listdir(src_path):
if "label" in filename :
label_path = src_path+filename
label_file = open(label_path,'r')
if "feature" in filename :
feature_name = filename.split('.')[0].split('_')[1]
feature_file_dct[feature_name] = open(src_path+filename,"r")
# get entire sets size
number_of_sets = int(os.popen("wc -l "+label_path).readlines()[0].split()[0])
# get result set row number list
rows = sorted(random.sample(range(0,number_of_sets),result_size))
result_file = open(result_file_name,'w')
# headline
headline = "node1,node2"
for feature_name in sorted(feature_file_dct.keys()):
headline+=","
headline+=feature_name
headline += ",label\n"
result_file.write(headline)
idx = 0
lines = {}
label_line = ""
while (len(rows)>0) :
if idx % 10000 == 0 : print idx
label_line = label_file.readline().strip()
for feature_name in sorted(feature_file_dct.keys()):
lines[feature_name] = feature_file_dct[feature_name].readline().strip()
if idx == rows[0] :
node1,node2,label = label_line.split('\t')
result_line=node1+','+node2
for feature_name in sorted(feature_file_dct.keys()):
result_line += (','+lines[feature_name].split('\t')[2])
if label == '0':
label = 'no'
else:
label = 'yes'
result_line += (','+label+'\n')
result_file.write(result_line)
rows.pop(0)
idx+=1
result_file.close() | [
[
8,
0,
0.0484,
0.0806,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0968,
0.0161,
0,
0.66,
0.05,
688,
0,
1,
0,
0,
688,
0,
0
],
[
1,
0,
0.1129,
0.0161,
0,
0.66,
... | [
"'''\nCreated on Dec 7, 2011\n\n@author: jeongjin\n'''",
"import os",
"import random",
"src_path = \"/Users/jeongjin/Dropbox/224w/data/AgraphTestData/\"",
"label_path = \"\"",
"label_file = None",
"feature_file_dct = {}",
"result_size = 500000",
"result_file_name = src_path+\"data_\"+str(result_size... |
import re
__author__ = 'N Tech2'
""" Giovanni's MicroCompiler Demo
<program> ::= { <id> ; <vars > <stmtlist> }
<vars> ::= V { <id> ; } % DECLARATIONS
<stmtlist> ::= <stmt> { ; <stmt> }
<stmt> ::= P <id> | <id> = <expr>
<expr> ::= <factor> { (+ | -) <factor> } % No precedence
<factor> ::= ID | Number
"""
import sys
#===============================================================================
# # Lexical Analyser - the "Scanner" - Define the TokenTypes
#===============================================================================
tokenNames =\
[ "unknownToken", "idsym", "assignsym", "leftbrace", "rightbrace",
"varsym", "semicolon", "whilesym", "leftbracket", "rightbracket",
"printsym", "ifsym", "equals", "stringsym", "lessthan", "greaterthan",
"number", "plus", "minus", "endsym" ,"elsesym","declaresym","forsym",
"andsym","elifsym","continuesym","nonesym","breaksym","coment","programsym",
"leftsquarebrace","rightsquarebrace","lessthanequal","colon","comma",
"dot"," greaterthanequal","jumpeq","jumpne","andop","orop","readint",
"writeint","readch","writech","mpy","div","quote ","stringsym","arraysym",
"readsym","endfile"]
# define the tokens as variables
unknownToken, idsym, assignsym, leftbrace, rightbrace,\
varsym, semicolon, whilesym, leftbracket, rightbracket,\
printsym, ifsym, equals,stringsym, lessthan, greaterthan,\
number, plus, minus,elsesym,declaresym,forsym,andsym,elifsym,\
continuesym,breaksym,nonesym,comment,leftsquarebrace,rightsquarebrace,\
lessthanequal,colon,comma,dot, greaterthanequal,jumpeq,jumpne,\
andop,orop,endfile,readint,writeint,readch,writech,\
mpy,div,quote,stringsym,arraysym,readsym,programsym,\
endfile = range(0, len(tokenNames))
#===============================================================================
class symbol:
#===============================================================================
name = None # String representation
token = None; # Corresponding token
address = 0; # For variables, their runtime address
value = None # on defined for numbers
def __init__(self, name, token, value = 0):
self.name = name
self.token = token
self.address = 0 # for identifiers, their address
self.value = value # for numbers, their value
symtbl = {}; # The Symbol Table, a dictionary of symbols indexed by name
#======================================================================
# GLOBALS for output of Lexical Analyser
# Set by each call to GeToken()
token = None; # A symbol
line = "\n" # the complex source file as a string
charIndex = 0 # the position in the source
linenumber= 0 # The current number
EOF = chr(0)
#======================================================================
# Run Time Code Generation Variables
varptr = 500 # Arbitrary base address of memory for variables
codeptr = 4 # Address to output next instruction (for code)
#===============================================================================
# Symbol Table Management Routines
#===============================================================================
#===============================================================================
def addToSymTbl (name, token):
#===============================================================================
symtbl[name] = symbol(name, token) # Add a new symbol to the dictionary
return symtbl[name]
#===============================================================================
def lookup (thisName):
#===============================================================================
"# Find a given identifier in the Symbol Table, Return the symtbl entry"
if symtbl.has_key(thisName): # thisName has been seen before
return symtbl[thisName] # return the symtbl entry
else: return None
#===============================================================================
def initSymTbl():
#===============================================================================
"# Initialise Symbol Table, and preload reserved words"
addToSymTbl('var', varsym)
addToSymTbl('program', programsym)# VAR
addToSymTbl('while', whilesym) # WHILE
addToSymTbl('print', printsym) # PRINT
addToSymTbl('else', elsesym)
addToSymTbl('elif', elifsym)
addToSymTbl('if', ifsym)
addToSymTbl('declare', declaresym)
addToSymTbl('for', forsym)
addToSymTbl('None', nonesym)
addToSymTbl('continue', continuesym)
addToSymTbl('readint', readint) #READINT
addToSymTbl('writeint', writeint) #READINT
addToSymTbl('readch', readch) #READINT
addToSymTbl('writech', writech)
addToSymTbl('read', readsym)#READINT
# Now add symbols - NB only single character symbols are here
# multicharacter one like ">=" are still to do
addToSymTbl( '=', assignsym)
addToSymTbl( '<', lessthan)
addToSymTbl( '>', greaterthan)
addToSymTbl( '{', leftbrace )
addToSymTbl( '}', rightbrace)
addToSymTbl( '(', leftbracket)
addToSymTbl( ')', rightbracket)
addToSymTbl( '+', plus )
addToSymTbl( '-', minus)
addToSymTbl( ';', semicolon)
addToSymTbl( 'break', breaksym)
addToSymTbl( '*', mpy)
addToSymTbl( '/', div)
addToSymTbl( '[', leftsquarebrace)
addToSymTbl( ']', rightsquarebrace)
addToSymTbl( ':', colon)
addToSymTbl( ',', comma)
addToSymTbl( '.', dot)
addToSymTbl( '==', jumpeq)
addToSymTbl( '!=', jumpne)
addToSymTbl( '&&', andop)
addToSymTbl( '||', orop)
addToSymTbl( '"',quote)
addToSymTbl( EOF, endfile)
#===============================================================================
# Scanner Diagnostics
#===============================================================================
def printToken(tok):
#===============================================================================
" - display the specified token."
if tok.token == idsym:
print "Token = %10s, %-10s adr = %3d" %\
(tokenNames[tok.token], tok.name, tok.address)
elif tok.token == number:
print "Token = %10s %d" % (tokenNames[tok.token], tok.value)
else:
print "Token = %10s" % tokenNames[tok.token]
#==============================?=================================================
def dumpSymTbl():
#===============================================================================
""" Dump all the tokens in the symboltable """
print(" *** Symbol Table ***")
for name in symtbl.keys(): # keys is a list of the names (printable form of tokens)
tok = symtbl[name]
if tok.token == idsym:
printToken(tok)
#===============================================================================
def getch():
#===============================================================================
global line
global charIndex
global linenumber
while True:
if charIndex < len(line): # See if used up current line
ch = line[charIndex] # if not, get character
charIndex = charIndex+1 # & move pointer for next time
else:
# line = f.readline()
# if line == "": line = EOF
print "--> ",
line = raw_input() +"\n" # read new line, adding \n so it's like f.readline()
charIndex = 0 # & reset character pointer
linenumber = linenumber + 1
continue
if ch == "\n":
ch = " "
if ch == '?':
dumpSymTbl()
continue
return ch
#===============================================================================
def ungetch():
#===============================================================================
""" Unget the next character peeked at when building variables, numbers
and when distinguishing between >= and > ...
"""
global charIndex;
charIndex = charIndex-1;
#===============================================================================
def getoken():
#===============================================================================
""" GETOKEN - Put next token into the global TOKEN """
global token
x=0
ch = getch() # skip whitespace
while ch in ["\t", " ", "\n"]:
ch = getch()
# If ch is alphabetic then this is start of reserved word or an identifier
if ch.isalpha(): # Letter therefore it's either identifier or reserved word
name = ""
while ch.isalpha() or ch.isdigit() or ch == "_":
name = name + ch
ch = getch()
ungetch() # let terminator be used next time
token = lookup(name) # See if token's known
if token is None: # if not
token = addToSymTbl(name, idsym) # add as 'idsym'-IDENTIFIER
return # we've set token.token to either id or tokentype of reserved word
elif ch in ["=", "{", "}", "(", ")", "[","]", "+", "-","*", "/", ";","!", "==",",","<=",">=",":", EOF]:
token = lookup(ch) # preloaded with appropriate token
elif ch.isdigit():
# In the real version, build number and don't forget to end with ungetch()
while(ch.isdigit() == True):
x = str(x) + str(ch)
ch = getch()
ch = ungetch()
token = symbol(x, number, value = int(x)) # simplistic SINGLE DIGIT Ascii to Binary
return
# elif ch == "-":
# x = ""
# no =""
# ch = getch()
# if ch.isdigit() ==True:
# while ch.isdigit():
# x = str(x) + str(ch)
# ch = getch()
#
# ch = ungetch()
#
# no = "-" + str(x)
#
# token = symbol(no, number, value = int(no))
elif ch =='#':
comment = ""
str1 =""
ch = getch()
while(ch != '.'):
str1 = str(str1) + str(ch)
ch = getch()
ch = ungetch()
comment1 = "#" + str(str1)
token = symbol(comment1, comment, value = str(comment1)) # simplistic SINGLE DIGIT Ascii to Binary
return
elif ch =='"':
a =""
ch = getch()
while ch != '"':
a = str(a) + str(ch)
ch = getch()
ch = getch()
token = symbol(a, stringsym, value = str(a)) # simplistic SINGLE DIGIT Ascii to Binary
return
elif ch =="<":
ch = getch()
if ch == "=":
lt =""
lt ="<" + "="
token = symbol(lt, lessthanequal, value = str(lt)) # simplistic SINGLE DIGIT Ascii to Binary
return
else:
ch == ungetch()
token = symbol("<", lessthan, value = "<") # simplistic SINGLE DIGIT Ascii to Binary
return
elif ch ==">":
gt =""
ch = getch()
if ch == "=":
gt =">" + "="
ch = getch()
token = symbol(gt, lessthanequal, value = str(gt)) # simplistic SINGLE DIGIT Ascii to Binary
return
else:
ch == ungetch()
token = symbol(">", greaterthan, value = ">") # simplistic SINGLE DIGIT Ascii to Binary
return
else:
print "Unknown character -->%s<- decimal %d" % (ch,ord(ch))
sys.exit(1) # Abort Compilation
#======================================================================
# THE GRAMMAR
# <program> ::= { <id> ; <vars > <stmtlist> }
# <vars> ::= var { <id> ; } % DECLARATIONS
# <array> ::= [<expr>]
# <stmtlist> ::= <stmt> { ; <stmt> }
# <stmt> ::= print <id>
# <id> = <expr>
# <expr> ::= <factor> { (+ | - | * | /) <factor> } % No precedence
# <factor> ::= [+/-] ID | Number
#======================================================================
# Centralised Parser Error Message handler
#======================================================================
#===============================================================================
def error (msg):
#===============================================================================
print line
print "-" * charIndex,"^"
print("Error on %d - %s\n" % (number, msg))
printToken(token)
print("\n")
#===============================================================================
def emit (memadr, opcode, parameter):
#===============================================================================
"""EMIT CODE - Emit a of code with a Parameter
if first arg is zero - (the memory address), use and incr CODEPTR"""
global codeptr
if (memadr == 0):
memadr = codeptr
codeptr = codeptr+1
print "%6d %-8s %-7s" % (memadr, opcode, parameter)
#======================================================================
# VARIABLE DECLARATIONS
# <vars> ::= V { <id> ; }
#===============================================================================
def vars() :
#===============================================================================
ta = 0
tn = []
global varptr;
getoken();
if token.token == idsym:
ta = token.address
tn = token.name
getoken()
if token.token == leftsquarebrace:
getoken()
if token.token == number:
getoken()
if token.token == rightsquarebrace:
getoken()
else:
error("] expected")
else: error("number expected")
else:
if ta != 0:
print("%c already declared\n", tn);
# assignStmt()
else:
symtbl[tn].address = varptr;
varptr = varptr +1
if token.token == assignsym:
getoken()
expression()
if token.token == comma:
vars()
elif token.token == semicolon : getoken()
else: error("comma or semicolon expected in declaration")
#===============================================================================
def array():
#===============================================================================
global array;
getoken()
while (token.token == number):
print("#array address")
emit(0, "constant", token.value)
emit(0, "constant", token.value)
emit(0, "constant", token.value)
emit(0, "constant", token.value)
emit(0, "constant", 4)
getoken();
if token.token == rightsquarebrace:getoken();
if token.token == assignsym:getoken();
while( token.token == number):
print("#store value")
emit(0, "load", 10)
emit(0, "add", 12)
emit(0, "store", 1)
emit(0, "loadv", token.value)
emit(0, "store-ind", 0)
getoken();
#======================================================================
# STMTLIST
# <stmtlist> ::= <stmt> { ; <stmt> }
#===============================================================================
def stmtList():
#===============================================================================
stmt()
while (token.token != rightbrace):
stmt()
print("\n#*** Compilation finished ***\n")
#======================================================================
# STMT
#===============================================================================
def stmt():
#===============================================================================
""" <stmt> ::= print <expression> | <id> = <expression>
"""
global codeptr
thisStmtAdr = codeptr # Jump DEMO - not part of Stmt
if token.token == arraysym:
array()
if token.token == printsym:
printStmt()
if token.token == number:
expression()
elif token.token == leftbracket:
getoken()
elif token.token == leftbrace:
getoken()
elif token.token == idsym:
assignStmt()
elif token.token == stringsym:
# emit(0, "call",40)
getoken()
elif token.token == assignsym:
getoken()
elif token.token == comment:
getoken()
elif token.token == breaksym:
getoken()
elif token.token == ifsym:
ifStmt()
elif token.token == elsesym:
elseStmt()
elif token.token == whilesym:
whileStmt()
elif token.token == readint:
readIntStmt()
elif token.token == readch:
readChStmt()
elif token.token == writeint:
writeIntStmt()
elif token.token ==lessthanequal:
getoken()
elif token.token ==greaterthanequal:
getoken()
elif token.token == writech:
writeChStmt()
elif token.token == rightbracket:
getoken()
elif token.token == semicolon:
getoken()
elif token.token == comma:
getoken()
elif token.token == rightbrace:
print("\n#*** Compilation finished ***\n")
else:
error("Expected start of a statement")
# emit (0, "return", thisStmtAdr) Jump DEMO need in break program
#===============================================================================
def printStmt():
#===============================================================================
""" <printStmt> ::= print <expression>"""
getoken()
# skip "print"
expression()
emit(0, "writeint", 0)
stmt()
# if token.token == rightbrace:
# print("\n*** Compilation finished ***\n")
#===============================================================================
def assignStmt():
#===============================================================================
"""
<id> = <expression>
"""
whichidentifier = token # Remember which ID on Left
getoken() # Get token after identifier
if token.token == jumpne:
srcfile.read()
getoken()
elif token.token == assignsym:
getoken()
elif token.token == leftsquarebrace:
array()
elif token.token == jumpeq:
getoken()
elif token.token == rightbracket:
getoken()
elif token.token ==lessthanequal:
getoken()
elif token.token ==greaterthanequal:
getoken()
# elif token.token == idsym: factor()
else:
error("Expected = in assignment statement")
expression()
# Save result into LHS runtime address
#===============================================================================
def ifStmt():
#if-then-else
#===============================================================================
""" <ifStmt> ::= if <expression>"""
getoken() # skip "if"
emit(0, "compare",60)
expression()
stmt()
if token.token == rightbrace: getoken()
#===============================================================================
def elseStmt():
#if-then-else
#===============================================================================
""" <elseStmt> ::= else <expression>"""
getoken()
emit(0, "store", 888)
stmt()
emit(0, "return",0)
if token.token == rightbrace: getoken()
#===============================================================================
def whileStmt():
#===============================================================================
""" <whileStmt> ::= while (condition)statement"""
getoken()
emit(0, "compare",50)
expression()
stmt()
emit(0, "increment", 1)
emit(0, "jumpi", 14)
#===============================================================================
def expression():
#===============================================================================
"""
Leaves result in ACC at runtime
Use addresses 999 & 998 as Temporary variables
<expression> ::= <factor> { (+ | -) <factor> }
"""
# while token.token == plus or token.token == minus or token.token == mpy or token.token == div or token.token == lessthan or token.token == greaterthan or token.token == jumpne or token.token == jumpeq:
# op = token # remember +/-
# getoken() # skip past +/-
# emit(0, "store", 999) # Save current result
# factor()
#
#
# if token.token == leftbracket:
# getoken()
#1st number
if token.token == leftbracket: getoken()
factor()
while token.token == plus or token.token == minus or token.token == mpy or token.token == div or token.token == lessthan or token.token == greaterthan or token.token == jumpne or token.token == jumpeq or token.token == lessthanequal or token.token == greaterthanequal:
op = token # remember +/-
getoken()
# skip past +/-
emit(0, "store", 997)
# Save current result
if token.token == leftbracket:
getoken()
factor()
if token.token == plus:
emit(0, "loadv", 999)
emit(0, "add", 999)
emit(0, "store", 5)
elif token.token == minus: # Subtract - have to swap operand order
emit(0, "store", 998)
emit(0, "load" , 999)
emit(0, "subtract", 998) # Leaves result in Acc
emit(0, "store", 6)
if token.token == rightbracket:getoken()
if op.token == plus:
emit(0, "loadv", 999)
emit(0, "add", 999)
emit(0, "store", 5)
if op.token == leftbracket:getoken()
elif op.token == minus: # Subtract - have to swap operand order
emit(0, "store", 998)
emit(0, "load" , 999)
emit(0, "subtract", 998)
emit(0, "store", 6)
if token.token == semicolon:
getoken()
elif op.token == mpy:
emit(0, "store", 998)
emit(0, "load", 999)
emit(0, "mpy", 998)
emit(0, "store", 7)
elif op.token == div:
emit(0, "store", 998)
emit(0, "load", 999)
emit(0, "div", 998)
emit(0, "store", 8)
if token.token == plus:
emit(0, "loadv", 999)
emit(0, "add", 999)
emit(0, "store", 5)
elif token.token == minus: # Subtract - have to swap operand order
emit(0, "store", 998)
emit(0, "load" , 999)
emit(0, "subtract", 998)
emit(0, "store", 6)
elif op.token == mpy:
emit(0, "store", 998)
emit(0, "load", 999)
emit(0, "mpy", 998)
emit(0, "store", 7)
elif op.token == div:
emit(0, "store", 998)
emit(0, "load", 999)
emit(0, "div", 998)
emit(0, "store", 8)
elif op.token == lessthan:
emit(0, "store", 998)
emit(0, "compare", 999)
emit(0, "jumplt", 80)
emit(0, "loadv", 0)
emit(0, "store", 9)
elif op.token == greaterthan:
emit(0, "store", 998)
emit(0, "compare", 999)
emit(0, "jumpgt", 81)
emit(0, "loadv", 0)
emit(0, "store", 10)
elif op.token == lessthanequal:
emit(0, "store", 998)
emit(0, "compare", 999)
emit(0, "jumplt", 80)
emit(0, "loadv", 0)
emit(0, "store", 9)
elif op.token == greaterthanequal:
emit(0, "store", 998)
emit(0, "compare", 999)
emit(0, "jumpgt", 81)
emit(0, "loadv", 0)
emit(0, "store", 10)
#not working
elif op.token == jumpne:
emit(0, "store", 998)
emit(0, "compare", 999)
emit(0, "jumpne", 82)
emit(0, "loadv", 0)
emit(0, "store", 11)
elif op.token == jumpeq:
emit(0, "store", 998)
emit(0, "compare", 999)
emit(0, "jumpeq", 83)
#===============================================================================
def factor():
#===============================================================================
"""
# FACTOR() - leaves result in ACC at runtime
<factor> ::= identifier | number
"""
if token.token == plus:
getoken()
#- (unary)
elif token.token == minus:
getoken()
if token.token == idsym:
emit(0, "load", token.address)
getoken()
elif token.token == stringsym:
# emit(0, "call",40)
getoken()
elif token.token == number:
emit(0, "loadv", token.value)
# emit(0, "store", 1)
getoken()
elif token.token == comment:
getoken()
# print "token",tokenNames[token.token]
# elif token.token == assignsym:
# getoken()
elif token.token == leftbracket:
getoken()
# print "this is token",tokenNames[token.token]
elif token.token == leftsquarebrace: getoken()
elif token.token == rightbracket:
getoken()
elif token.token == breaksym:
getoken()
elif token.token == lessthanequal:
getoken()
elif token.token == greaterthanequal:
getoken()
elif token.token == rightsquarebrace:
getoken()
elif token.token == semicolon:
getoken()
elif token.token == leftbrace:
getoken()
elif token.token == rightbrace:
print("\n#*** Compilation finished ***\n")
else:
error("Start Of Factor Expected")
#===============================================================================
def program():
#===============================================================================
if token.token == leftbrace:
getoken()
if token.token == programsym:
getoken()
# else: error("Program start with 'program' keyword")
if token.token == idsym:
getoken()
# else: error("Program name expected")
if token.token == semicolon:
getoken()
# else: error("Semicolon expected")
if token.token == declaresym :
vars()
if token.token == varsym :
vars()
stmtList()
if token.token ==rightbrace:
print "***Compilation Finished****"
#======================================================================
def main():
#======================================================================
global line
global srcfile
global charIndex
initSymTbl()
with open("comment.txt") as line1:
out1file = open('output.obj','w')
line = line1.read()
out1file.write("hello")
# print line
charIndex = 0
debugScanner = False
if debugScanner: # Scanner Test Routine - Read a line and display the tokens
getoken()
while token.token is not None: # Skeleton for testing Scanner
printToken(token)
y = str(token)
out1file.write(y)
getoken()
sys.exit(1)
else:
getoken() # Parse Program according to the grammar
program()
emit(0, "load", 0)
"""
emit(0, "constant", "'A'") #need in break,comment,exitloop,writer-if-read-write-ch program
emit(0, "constant", 10)
emit(0, "constant", 12)
emit(0, "constant", 25)
emit(0, "constant", -10)
"""
main()
getoken()
#=======================================================================
# *** That's it folks - written by Giovanni Moretti - April 27, 2011 ***
#=======================================================================
__author__ = 'N Tech2'
| [
[
1,
0,
0.0011,
0.0011,
0,
0.66,
0,
540,
0,
1,
0,
0,
540,
0,
0
],
[
14,
0,
0.0033,
0.0011,
0,
0.66,
0.0238,
777,
1,
0,
0,
0,
0,
3,
0
],
[
8,
0,
0.0137,
0.0132,
0,
0... | [
"import re",
"__author__ = 'N Tech2'",
"\"\"\" Giovanni's MicroCompiler Demo\n\n<program> ::= { <id> ; <vars > <stmtlist> }\n<vars> ::= V { <id> ; } % DECLARATIONS\n\n<stmtlist> ::= <stmt> { ; <stmt> }\n<stmt> ::= P <id> | <id> = <expr>",
"... |
import re
__author__ = 'YeeHin Kwok'
""" Giovanni's MicroCompiler Demo
<program> ::= { <id> ; <vars > <stmtlist> }
<vars> ::= V { <id> ; } % DECLARATIONS
<stmtlist> ::= <stmt> { ; <stmt> }
<stmt> ::= P <id> | <id> = <expr>
<expr> ::= <factor> { (+ | -) <factor> } % No precedence
<factor> ::= ID | Number
"""
import sys
import shlex
#===============================================================================
# # Lexical Analyser - the "Scanner" - Define the TokenTypes
#===============================================================================
tokenNames = \
[ "unknownToken", "idsym", "assignsym", "leftbrace", "rightbrace",
"varsym", "semicolon", "whilesym", "leftbracket", "rightbracket",
"printsym", "ifsym", "equals", "lessthan", "greaterthan",
"number", "plus", "minus", "mpy", "div", "elsesym", "declaresym", "forsym", "andsym", "elifsym", "dosym", "returnsym",
"continuesym", "breaksym", "nonesym", "programsym", "functionsym", "leftsquarebrace", "rightsquarebrace",
"lessthanequal", "colon", "comma", "comment", "commentstr", "dot", " greaterthanequal", "jumpeq", "jumpne",
"andop", "orop", "quote ", "stringsym", "arraysym", "readsym", "endfile"]
# define the tokens as variables
unknownToken, idsym, assignsym, leftbrace, rightbrace, \
varsym, semicolon, whilesym, leftbracket, rightbracket, \
printsym, ifsym, equals, lessthan, greaterthan, \
number, plus, minus, mpy, div, elsesym, declaresym, forsym, andsym, elifsym, dosym, returnsym, \
continuesym, breaksym, nonesym, programsym, functionsym, leftsquarebrace, rightsquarebrace, \
lessthanequal, colon, comma, comment, commentstr, dot, greaterthanequal, jumpeq, jumpne, \
andop, orop, quote, stringsym, arraysym, readsym, endfile = range(0, len(tokenNames))
#===============================================================================
class symbol:
#===============================================================================
name = None # String representation
token = None; # Corresponding token
address = 0; # For variables, their runtime address
value = None # on defined for numbers
def __init__(self, name, token, value=0):
self.name = name
self.token = token
self.address = 0 # for identifiers, their address
self.value = value # for numbers, their value
symtbl = {}; # The Symbol Table, a dictionary of symbols indexed by name
#======================================================================
# GLOBALS for output of Lexical Analyser
# Set by each call to GeToken()
token = None; # A symbol
line = "\n" # the complex source file as a string
charIndex = 0 # the position in the source
linenumber = 0 # The current number
i = 100
j = 100
counterafter = i
counterafter1 = j
EOF = chr(0)
#======================================================================
# Run Time Code Generation Variables
varptr = 500 # Arbitrary base address of memory for variables
codeptr = 10 # Address to output next instruction (for code)
#===============================================================================
# Symbol Table Management Routines
#===============================================================================
#===============================================================================
def addToSymTbl (name, token):
#===============================================================================
symtbl[name] = symbol(name, token) # Add a new symbol to the dictionary
return symtbl[name]
#===============================================================================
def lookup (thisName):
#===============================================================================
"# Find a given identifier in the Symbol Table, Return the symtbl entry"
if symtbl.has_key(thisName): # thisName has been seen before
return symtbl[thisName] # return the symtbl entry
else: return None
#===============================================================================
def initSymTbl():
#===============================================================================
"# Initialise Symbol Table, and preload reserved words"
addToSymTbl('var', varsym) # VAR
addToSymTbl('program', programsym)
addToSymTbl('function', functionsym)
addToSymTbl('while', whilesym) # WHILE
addToSymTbl('print', printsym) # PRINT
addToSymTbl('else', elsesym)
addToSymTbl('elif', elifsym)
addToSymTbl('if', ifsym)
addToSymTbl('declare', declaresym)
addToSymTbl('for', forsym)
addToSymTbl('None', nonesym)
addToSymTbl('continue', continuesym)
addToSymTbl('read', readsym) # READINT
addToSymTbl('do', dosym)
addToSymTbl('return', returnsym)
# Now add symbols - NB only single character symbols are here
# multicharacter one like ">=" are still to do
addToSymTbl('=', assignsym)
addToSymTbl('#', comment)
addToSymTbl('<', lessthan)
addToSymTbl('>', greaterthan)
addToSymTbl('{', leftbrace)
addToSymTbl('}', rightbrace)
addToSymTbl('(', leftbracket)
addToSymTbl(')', rightbracket)
addToSymTbl('+', plus)
addToSymTbl('-', minus)
addToSymTbl(';', semicolon)
addToSymTbl('break', breaksym)
addToSymTbl('*', mpy)
addToSymTbl('/', div)
addToSymTbl('[', leftsquarebrace)
addToSymTbl(']', rightsquarebrace)
addToSymTbl(':', colon)
addToSymTbl(',', comma)
addToSymTbl('.', dot)
addToSymTbl('==', jumpeq)
addToSymTbl('!=', jumpne)
addToSymTbl('&&', andop)
addToSymTbl('||', orop)
addToSymTbl('"', quote)
addToSymTbl(EOF, endfile)
#===============================================================================
# Scanner Diagnostics
#===============================================================================
def printToken(tok):
#===============================================================================
" - display the specified token."
if tok.token == idsym:
print "Token = %10s, %-10s adr = %3d" % \
(tokenNames[tok.token], tok.name, tok.address)
elif tok.token == number:
print "Token = %10s %d" % (tokenNames[tok.token], tok.value)
else:
print "Token = %10s" % tokenNames[tok.token]
#==============================?=================================================
def dumpSymTbl():
#===============================================================================
""" Dump all the tokens in the symboltable """
print(" *** Symbol Table ***")
for name in symtbl.keys(): # keys is a list of the names (printable form of tokens)
tok = symtbl[name]
if tok.token == idsym:
printToken(tok)
#===============================================================================
def getch():
#===============================================================================
global line
global charIndex
global linenumber
while True:
if charIndex < len(line): # See if used up current line
ch = line[charIndex] # if not, get character
charIndex = charIndex + 1 # & move pointer for next time
else:
# line = f.readline()
# if line == "": line = EOF
print "#End of File"
print "#--> ",
line = raw_input() + "\n" # read new line, adding \n so it's like f.readline()
# line = srcfile.read()
charIndex = 0 # & reset character pointer
linenumber = linenumber + 1
continue
if ch == "\n":
ch = " "
if ch == '?':
dumpSymTbl()
continue
return ch
#===============================================================================
def ungetch():
#===============================================================================
""" Unget the next character peeked at when building variables, numbers
and when distinguishing between >= and > ...
"""
global charIndex;
charIndex = charIndex - 1;
#===============================================================================
def getoken():
#===============================================================================
""" GETOKEN - Put next token into the global TOKEN """
global token
global i
global m
global counterafter
global counterafter1
x = 0
ch = getch() # skip whitespace
while ch in ["\t", " ", "\n"]:
ch = getch()
# If ch is alphabetic then this is start of reserved word or an identifier
if ch.isalpha(): # Letter therefore it's either identifier or reserved word
name = ""
while ch.isalpha() or ch.isdigit() or ch == "_":
name = name + ch
ch = getch()
ungetch() # let terminator be used next time
token = lookup(name) # See if token's known
if token is None: # if not
token = addToSymTbl(name, idsym) # add as 'idsym'-IDENTIFIER
return # we've set token.token to either id or tokentype of reserved word
elif ch in ["{", "}", "(", ")", "[", "]", "+", "-", "*", "/", ";", ",", ":", EOF]:
token = lookup(ch) # preloaded with appropriate token
elif ch.isdigit():
# In the real version, build number and don't forget to end with ungetch()
while(ch.isdigit() == True):
x = str(x) + str(ch)
ch = getch()
ch = ungetch()
token = symbol(x, number, value=int(x)) # simplistic SINGLE DIGIT Ascii to Binary
return
# elif ch == "-":
# x = ""
# no =""
# ch = getch()
# if ch.isdigit() ==True:
# while ch.isdigit():
# x = str(x) + str(ch)
# ch = getch()
#
# ch = ungetch()
#
# no = "-" + str(x)
#
# token = symbol(no, number, value = int(no))
elif ch == '#':
str1 = ""
ch = getch()
while(ch != " "):
str1 = str(str1) + str(ch)
ch = getch()
ch = getch()
token = symbol(str1, commentstr, value=str(str1)) # simplistic SINGLE DIGIT Ascii to Binary
print("#comment: " + str(str1))
return
elif ch == '"':
a = ""
ch = getch()
counterafter1 =counterafter
i=counterafter
if counterafter != 100:
counterafter=counterafter+4;
counterafter = i
while (ch != '"'):
a = str(a) + str(ch)
if ch != " ":
b = "'"+ch+"'"
emit(i, "constant",b)
ch = getch()
i=i+1
emit(i, "constant", 13)
emit(i+1, "constant", 0)
# emit(i+2, "writech", '')
emit(i+2, "return", '')
ch = getch()
counterafter=i+3
token = symbol(a, stringsym, value=str(a)) # simplistic SINGLE DIGIT Ascii to Binary
# printMsg()
return
elif ch == "<":
ch = getch()
if ch == "=":
lt = ""
lt = "<" + "="
token = symbol(lt, lessthanequal, value=str(lt)) # simplistic SINGLE DIGIT Ascii to Binary
return
else:
ch == ungetch()
token = symbol("<", lessthan, value="<") # simplistic SINGLE DIGIT Ascii to Binary
return
elif ch == "!":
ne = ""
ch = getch()
if ch == "=":
ne = "!" + "="
token = symbol(ne, jumpne, value=str(ne)) # simplistic SINGLE DIGIT Ascii to Binary
return
else:
ch == ungetch()
token = symbol("!", NOT , value="!") # simplistic SINGLE DIGIT Ascii to Binary
return
elif ch == "=":
eq = ""
ch = getch()
if ch == "=":
eq = "=" + "="
token = symbol(eq, jumpeq, value=str(eq)) # simplistic SINGLE DIGIT Ascii to Binary
return
else:
ch == ungetch()
token = symbol("=", assignsym, value="=") # simplistic SINGLE DIGIT Ascii to Binary
return
elif ch == ">":
gt = ""
ch = getch()
if ch == "=":
gt = ">" + "="
token = symbol(gt, lessthanequal, value=str(gt)) # simplistic SINGLE DIGIT Ascii to Binary
return
else:
ch == ungetch()
token = symbol(">", greaterthan, value=">") # simplistic SINGLE DIGIT Ascii to Binary
return
else:
print "Unknown character -->%s<- decimal %d" % (ch, ord(ch))
sys.exit(1) # Abort Compilation
#======================================================================
# THE GRAMMAR
# <program> ::= { <id> ; <vars > <stmtlist> }
# <vars> ::= var { <id> ; } % DECLARATIONS
# <array> ::= [<expr>]
# <stmtlist> ::= <stmt> { ; <stmt> }
# <stmt> ::= print <id>
# <id> = <expr>
# <expr> ::= <factor> { (+ | - | * | /) <factor> } % No precedence
# <factor> ::= [+/-] ID | Number
#======================================================================
# Centralised Parser Error Message handler
#======================================================================
#===============================================================================
def error (msg):
#===============================================================================
print line
print "-" * charIndex, "^"
print("Error on %d - %s\n" % (number, msg))
printToken(token)
print("\n")
#===============================================================================
def emit (memadr, opcode, parameter):
#===============================================================================
"""EMIT CODE - Emit a of code with a Parameter
if first arg is zero - (the memory address), use and incr CODEPTR"""
global codeptr
if (memadr == 0):
memadr = codeptr
codeptr = codeptr + 1
print "%6d %-8s %-7s" % (memadr, opcode, parameter)
#======================================================================
# VARIABLE DECLARATIONS
# <vars> ::= V { <id> ; }
#===============================================================================
def vars() :
#===============================================================================
ta = 0
tn = []
global varptr;
getoken();
if token.token == idsym:
ta = token.address
tn = token.name
getoken()
if token.token == leftsquarebrace:
getoken()
if token.token == number:
# emit(0, "loadv",token.value)
# emit(0, "store", token.value+300)
array()
if token.token == rightsquarebrace:
getoken()
else:
error("var error: ] expected - 1")
else:
getoken()
elif tn == "i":
# print("#The array name is " + str(tn)+"\n")
if token.token == rightsquarebrace:
getoken()
else:
if ta != 0:
print("%c already declared\n", tn);
#assignStmt()
else:
symtbl[tn].address = varptr;
varptr = varptr + 1
# emit(0, "load", varptr)
if token.token == assignsym:
getoken()
expression()
if token.token == rightbracket:
getoken()
if token.token == comma:
vars()
elif token.token == semicolon : getoken()
else: error("comma or semicolon expected in declaration")
#===============================================================================
def array():
#===============================================================================
global array;
# getoken()
while (token.token == number):
print("#array address")
emit(0, "store", token.value + 400)
print("#array value " +str(token.value))
getoken();
#======================================================================
# STMTLIST
# <stmtlist> ::= <stmt> { ; <stmt> }
#===============================================================================
def stmtList():
#===============================================================================
stmt()
while (token.token != rightbrace):
stmt()
#======================================================================
# STMT
#===============================================================================
def stmt():
#===============================================================================
""" <stmt> ::= print <expression|string>| read <vars> | <id> = <expression> |
if <condition> <stmt> [else <stmt>]| while <condition> <stmt>|
<stmtList> | do <stmsList> forever | break | continue
"""
global codeptr
thisStmtAdr = codeptr # Jump DEMO - not part of Stmt
# if token.token == arraysym:
# array()
if token.token == printsym:
printStmt()
elif token.token == readsym:
readStmt()
elif token.token == number:
expression()
elif token.token == idsym:
assignStmt()
elif token.token == ifsym:
ifStmt()
elif token.token == elsesym:
elseStmt()
elif token.token == whilesym:
whileStmt()
elif token.token == dosym:
doStmt()
elif token.token == returnsym:
expression()
elif token.token == continuesym:
continueStmt()
elif token.token == leftbracket:
getoken()
elif token.token == leftbrace:
getoken()
elif token.token == stringsym:
# print(str(token.name))
printMsg()
getoken()
elif token.token == assignsym:
getoken()
elif token.token == commentstr:
# print(str(token.name))
getoken()
elif token.token == breaksym:
getoken()
elif token.token == lessthanequal:
getoken()
elif token.token == greaterthanequal:
getoken()
elif token.token == jumpeq:
getoken()
elif token.token == jumpne:
getoken()
elif token.token == rightbracket:
getoken()
elif token.token == semicolon:
getoken()
elif token.token == comma:
getoken()
elif token.token == rightsquarebrace:
getoken()
elif token.token == rightbrace:
getoken()
else:
error("Expected start of a statement")
# emit (0, "return", thisStmtAdr) Jump DEMO need in break program
#===============================================================================
def printStmt():
#===============================================================================
""" <printStmt> ::= print <expression|string>"""
getoken()# skip "print"
stmt()
emit(0, "load", 501)
expression()
emit(0, "writeint", 502)
emit(0, "writeint", 7)
#===============================================================================
def printMsg():
#===============================================================================
""" <printMsg> ::= printMsg <expression>"""
# print("#"+str(counterafter)+ " counterafter")
# print("#"+str(counterafter1)+ " counterafter1")
# if counterafter != 100:
# emit(0,"loadv",counterafter )
emit(0, "loadv", counterafter1)
emit(0, "store", 1)
emit(0, "call", 400)
emit(400, "load-Ind", 0)
emit(401, "jumpeq", 405)
emit(402, "writech",0)
emit(403, "increment", 1)
emit(404, "jump", 400)
emit(405, "return", '')
#===============================================================================
def readStmt():
#===============================================================================
""" <readStmt> ::= read <vars>"""
getoken()
emit(0, "readint", 7)
emit(0, "store", 502)
getoken()
# writeStmt()
#===============================================================================
def writeStmt():
#===============================================================================
""" <writeStmt> ::= read <vars>"""
getoken()
# emit(0,"load", 501)
# emit(0, "writeint", 501)
#===============================================================================
def assignStmt():
#===============================================================================
"""
<id> = <expression>
"""
whichidentifier = token # Remember which ID on Left
getoken() # Get token after identifier
if token.token == assignsym:
getoken()
elif token.token == leftsquarebrace:
vars()
elif token.token == leftbrace:
vars()
elif token.token == jumpeq:
getoken()
elif token.token == jumpne:
getoken()
elif token.token == rightbracket:
getoken()
elif token.token == lessthanequal:
getoken()
elif token.token == comma:
getoken()
elif token.token == greaterthanequal:
getoken()
# elif token.token == idsym: factor()
else:
error("Expected = in assignment statement")
expression()
# Save result into LHS runtime address
#===============================================================================
def ifStmt():
# if-then-else
#===============================================================================
""" <ifStmt> ::= if <expression>"""
print("#IFSmt")
getoken() # skip "if"
expression()
stmt()
expression()
#===============================================================================
def elseStmt():
# if-then-else
#===============================================================================
""" <elseStmt> ::= else <expression>"""
print("#ElseSmt")
emit(200, "jump", 47) # less than 2 go to else
getoken()
stmt()
expression()
# emit(314, "jump", 22)
#===============================================================================
def whileStmt():
#===============================================================================
""" <whileStmt> ::= while (condition)statement"""
# emit(0, "load", 201)
emit(0, "store", 502)
getoken()
expression() # num>0
# emit(0, "jump", 22)
stmt()
#===============================================================================
def expression():
#===============================================================================
"""
Leaves result in ACC at runtime
Use addresses 999 & 998 as Temporary variables
<expression> ::= <factor> { (+ | -) <factor> }
"""
if token.token == leftbracket: getoken()
factor()
## 1st start==============================================================================
while token.token == plus or token.token == minus or token.token == mpy or token.token == div or token.token == lessthan or token.token == greaterthan or token.token == lessthanequal or token.token == greaterthanequal or token.token == jumpne or token.token == jumpeq:
op = token # remember -
getoken() # skip past -
# emit(0, "store", 997) # Save current result
factor()
if op.token == plus:
emit(0, "add", 502)
emit(0, "store", 502)
# emit(0, "jump", 22)
# if op.token == leftbracket:getoken()
if op.token == minus:
## 2nd start==============================================================================
if token.token == plus or token.token == minus or token.token == mpy or token.token == div:
op2 = token# remember *
getoken() # skip past *
factor()
if op2.token == plus: # Subtract - have to swap operand order
emit(0, "load", 210)
emit(0, "add", 203)
emit(0, "store", 500)
if op2.token == minus: # Subtract - have to swap operand order
emit(0, "load", 501)
emit(0, "subtract", 201)
emit(0, "store", 501)
if op2.token == mpy:
## 3rd start==============================================================================
while token.token == plus or token.token == minus or token.token == mpy or token.token == div:
op3 = token# remember *
getoken() # skip past *
factor()
if op3.token == plus: # Subtract - have to swap operand order
emit(0, "load", 210)
emit(0, "add", 203)
emit(0, "store", 500)
if op3.token == minus: # Subtract - have to swap operand order
emit(0, "load", 501)
emit(0, "subtract", 210)
emit(0, "store", 501)
if op3.token == mpy:
factor()
## 4th start==============================================================================
while token.token == plus or token.token == minus or token.token == mpy or token.token == div:
if token.token == plus:
op4 = token# remember +
getoken() # skip past +
factor()
if op4.token == plus: # Subtract - have to swap operand order
emit(0, "load", 210)
emit(0, "add", 203)
emit(0, "store", 500)
if token.token == minus:
op4 = token# remember -
getoken() # skip past -
factor()
if op4.token == minus: # Subtract - have to swap operand order
emit(0, "load", 210)
emit(0, "subtract", 203)
emit(0, "store", 500)
if token.token == mpy:
op4 = token
getoken()
factor()
if op4.token == mpy: # Subtract - have to swap operand order
emit(0, "load", 210)
emit(0, "mpy", 203)
emit(0, "store", 500)
if token.token == div:
op4 = token
getoken()
factor()
if op4.token == div: # Subtract - have to swap operand order
emit(0, "load", 210)
emit(0, "div", 203)
emit(0, "store", 500)
## 4th end==============================================================================
emit(0, "mpy", 205)
emit(0, "store", 501)
## 3rd end==============================================================================
emit(0, "mpy", 210)
emit(0, "store", 501)
## 2nd end==============================================================================
else:
emit(0, "load", 501)
emit(0, "subtract", 201)
emit(0, "store", 501)
emit(0, "jump", 24)
elif op.token == mpy:
emit(0, "load", 206)
emit(0, "mpy", 7)
emit(0, "store", 502)
elif op.token == minus: # Subtract - have to swap operand order
emit(0, "load", 590)
emit(0, "subtract", 201)
emit(0, "store", 501)
emit(0, "writeInt", 502)
elif op.token == div:
emit(0, "load", 502)
emit(0, "div", 202)
emit(0, "store", 7)
elif op.token == lessthan:
emit(0, "load", 501)
emit(0, "compare", 212)
emit(0, "jumplt", 300)
emit(300, "writeInt", 502)
elif op.token == greaterthan:
emit(0, "load", 208)
emit(0, "compare", 7)
emit(0, "jumpgt", 47)
elif op.token == lessthanequal:
emit(0, "load", 501)
emit(0, "compare", 212)
emit(0, "jumplt", 300)
emit(300, "writeInt", 502)
elif op.token == greaterthanequal:
emit(0, "load", 501)
emit(0, "compare", 212)
emit(0, "jumpgt", 300)
emit(300, "writeInt", 502)
elif op.token == jumpne:
emit(0, "load", 205)
emit(0, "compare", 502)
emit(0, "jumpne", 310)
emit(0, "writeInt", 0)
emit(0, "halt", 0)
emit(310, "writeInt", 502)
elif op.token == jumpeq:
emit(0, "load", 501)
emit(0, "compare", 200)
emit(0, "jumpeq", 300)
# emit(0, "halt", 0)
emit(300, "writeInt", 502)
emit(301, "jump",30)
#===============================================================================
def factor():
#===============================================================================
"""
# FACTOR() - leaves result in ACC at runtime
<factor> ::= identifier | number
"""
if token.token == plus:
getoken()
# - (unary)
elif token.token == minus:
getoken()
if token.token == idsym:
emit(0, "load", token.address)
getoken()
elif token.token == stringsym: #################
print("#String: " + str(token.name))
printMsg()
getoken()
elif token.token == number:
emit(0, "loadv", token.value)
emit(0, "store", 200 + token.value)
getoken()
elif token.token == commentstr:
# print ("#Comment: " + str(token.name))
getoken()
# elif token.token == assignsym:
# getoken()
elif token.token == leftbracket:
getoken()
# print "this is token",tokenNames[token.token]
elif token.token == leftsquarebrace: getoken()
elif token.token == rightbracket:
getoken()
elif token.token == breaksym:
emit(0,"halt", 0)
elif token.token == lessthanequal:
getoken()
elif token.token == greaterthanequal:
getoken()
elif token.token == jumpeq:
getoken()
elif token.token == rightsquarebrace:
getoken()
elif token.token == semicolon:
getoken()
elif token.token == comma:
getoken()
elif token.token == leftbrace:
getoken()
elif token.token == rightbrace:
print("")
elif token.token == ifsym:
ifStmt()
elif token.token == printsym:
getoken()
else:
error("Start Of Factor Expected")
#===============================================================================
def function():
#===============================================================================
if token.token == functionsym:
getoken()
if token.token == idsym:
getoken()
if token.token == varsym :
vars()
if token.token == declaresym :
vars()
if token.token == varsym :
vars()
if token.token == leftbrace:
vars()
stmtList()
stmtList()
if token.token == rightbrace:
print "#---Function Finished---"
#===============================================================================
def program():
#===============================================================================
if token.token == leftbrace:
getoken()
if token.token == programsym:
getoken()
# else: error("Program start with 'program' keyword")
if token.token == idsym:
getoken()
# else: error("Program name expected")
if token.token == semicolon:
getoken()
# else: error("Semicolon expected")
if token.token == declaresym :
vars()
if token.token == varsym :
vars()
if token.token == functionsym:
function()
if token.token == leftbrace:
getoken()
stmtList()
stmtList()
if token.token == rightbrace:
print "#***Compilation Finished****"
#======================================================================
def main():
#======================================================================
global line
global srcfile
global charIndex
initSymTbl()
with open("test.txt") as srcfile:
# out1file = open('output.obj','w')
line = srcfile.read()
# out1file.write("hello")
# print line
charIndex = 0
debugScanner = False
if debugScanner: # Scanner Test Routine - Read a line and display the tokens
getoken()
while token.token is not None: # Skeleton for testing Scanner
printToken(token)
# y = str(token)
# out1file.write(y)
getoken()
sys.exit(1)
else:
getoken() # Parse Program according to the grammar
program()
#===============================================================================
# Main Compiler starts here
#===============================================================================
print "#Microcompiler.py v0.2"
emit(0, "load", 9)
main()
# emit(0, "constant", "'A'") #need in break,comment,exitloop,writer-if-read-write-ch program
# emit(0, "constant", 10)
# emit(0, "constant", 12)
# emit(0, "constant", 25)
# emit(0, "constant", -10)
"""
srcfile = open('tiny_1.txt', 'r')
lexer = shlex.shlex(srcfile)
for token in lexer:
print repr(token)
"""
# getoken()
#=======================================================================
# *** That's it folks - written by Giovanni Moretti - April 27, 2011 ***
#=======================================================================
| [
[
1,
0,
0.0009,
0.0009,
0,
0.66,
0,
540,
0,
1,
0,
0,
540,
0,
0
],
[
14,
0,
0.0027,
0.0009,
0,
0.66,
0.02,
777,
1,
0,
0,
0,
0,
3,
0
],
[
8,
0,
0.0112,
0.0108,
0,
0.6... | [
"import re",
"__author__ = 'YeeHin Kwok'",
"\"\"\" Giovanni's MicroCompiler Demo\n\n<program> ::= { <id> ; <vars > <stmtlist> }\n<vars> ::= V { <id> ; } % DECLARATIONS\n\n<stmtlist> ::= <stmt> { ; <stmt> }\n<stmt> ::= P <id> | <id> = <expr>",... |
import re
__author__ = 'YeeHin Kwok'
""" Giovanni's MicroCompiler Demo
<program> ::= { <id> ; <vars > <stmtlist> }
<vars> ::= V { <id> ; } % DECLARATIONS
<stmtlist> ::= <stmt> { ; <stmt> }
<stmt> ::= P <id> | <id> = <expr>
<expr> ::= <factor> { (+ | -) <factor> } % No precedence
<factor> ::= ID | Number
"""
import sys
import shlex
#===============================================================================
# # Lexical Analyser - the "Scanner" - Define the TokenTypes
#===============================================================================
tokenNames = \
[ "unknownToken", "idsym", "assignsym", "leftbrace", "rightbrace",
"varsym", "semicolon", "whilesym", "leftbracket", "rightbracket",
"printsym", "ifsym", "equals", "lessthan", "greaterthan",
"number", "plus", "minus", "mpy", "div", "elsesym", "declaresym", "forsym", "andsym", "elifsym", "dosym", "returnsym",
"continuesym", "breaksym", "nonesym", "programsym", "functionsym", "leftsquarebrace", "rightsquarebrace",
"lessthanequal", "colon", "comma", "comment", "commentstr", "dot", " greaterthanequal", "jumpeq", "jumpne",
"andop", "orop", "quote ", "stringsym", "arraysym", "readsym", "endfile"]
# define the tokens as variables
unknownToken, idsym, assignsym, leftbrace, rightbrace, \
varsym, semicolon, whilesym, leftbracket, rightbracket, \
printsym, ifsym, equals, lessthan, greaterthan, \
number, plus, minus, mpy, div, elsesym, declaresym, forsym, andsym, elifsym, dosym, returnsym, \
continuesym, breaksym, nonesym, programsym, functionsym, leftsquarebrace, rightsquarebrace, \
lessthanequal, colon, comma, comment, commentstr, dot, greaterthanequal, jumpeq, jumpne, \
andop, orop, quote, stringsym, arraysym, readsym, endfile = range(0, len(tokenNames))
#===============================================================================
class symbol:
#===============================================================================
name = None # String representation
token = None; # Corresponding token
address = 0; # For variables, their runtime address
value = None # on defined for numbers
def __init__(self, name, token, value=0):
self.name = name
self.token = token
self.address = 0 # for identifiers, their address
self.value = value # for numbers, their value
symtbl = {}; # The Symbol Table, a dictionary of symbols indexed by name
#======================================================================
# GLOBALS for output of Lexical Analyser
# Set by each call to GeToken()
token = None; # A symbol
line = "\n" # the complex source file as a string
charIndex = 0 # the position in the source
linenumber = 0 # The current number
i = 100
j = 100
counterafter = i
counterafter1 = j
EOF = chr(0)
#======================================================================
# Run Time Code Generation Variables
varptr = 500 # Arbitrary base address of memory for variables
codeptr = 10 # Address to output next instruction (for code)
#===============================================================================
# Symbol Table Management Routines
#===============================================================================
#===============================================================================
def addToSymTbl (name, token):
#===============================================================================
symtbl[name] = symbol(name, token) # Add a new symbol to the dictionary
return symtbl[name]
#===============================================================================
def lookup (thisName):
#===============================================================================
"# Find a given identifier in the Symbol Table, Return the symtbl entry"
if symtbl.has_key(thisName): # thisName has been seen before
return symtbl[thisName] # return the symtbl entry
else: return None
#===============================================================================
def initSymTbl():
#===============================================================================
"# Initialise Symbol Table, and preload reserved words"
addToSymTbl('var', varsym) # VAR
addToSymTbl('program', programsym)
addToSymTbl('function', functionsym)
addToSymTbl('while', whilesym) # WHILE
addToSymTbl('print', printsym) # PRINT
addToSymTbl('else', elsesym)
addToSymTbl('elif', elifsym)
addToSymTbl('if', ifsym)
addToSymTbl('declare', declaresym)
addToSymTbl('for', forsym)
addToSymTbl('None', nonesym)
addToSymTbl('continue', continuesym)
addToSymTbl('read', readsym) # READINT
addToSymTbl('do', dosym)
addToSymTbl('return', returnsym)
# Now add symbols - NB only single character symbols are here
# multicharacter one like ">=" are still to do
addToSymTbl('=', assignsym)
addToSymTbl('#', comment)
addToSymTbl('<', lessthan)
addToSymTbl('>', greaterthan)
addToSymTbl('{', leftbrace)
addToSymTbl('}', rightbrace)
addToSymTbl('(', leftbracket)
addToSymTbl(')', rightbracket)
addToSymTbl('+', plus)
addToSymTbl('-', minus)
addToSymTbl(';', semicolon)
addToSymTbl('break', breaksym)
addToSymTbl('*', mpy)
addToSymTbl('/', div)
addToSymTbl('[', leftsquarebrace)
addToSymTbl(']', rightsquarebrace)
addToSymTbl(':', colon)
addToSymTbl(',', comma)
addToSymTbl('.', dot)
addToSymTbl('==', jumpeq)
addToSymTbl('!=', jumpne)
addToSymTbl('&&', andop)
addToSymTbl('||', orop)
addToSymTbl('"', quote)
addToSymTbl(EOF, endfile)
#===============================================================================
# Scanner Diagnostics
#===============================================================================
def printToken(tok):
#===============================================================================
" - display the specified token."
if tok.token == idsym:
print "Token = %10s, %-10s adr = %3d" % \
(tokenNames[tok.token], tok.name, tok.address)
elif tok.token == number:
print "Token = %10s %d" % (tokenNames[tok.token], tok.value)
else:
print "Token = %10s" % tokenNames[tok.token]
#==============================?=================================================
def dumpSymTbl():
#===============================================================================
""" Dump all the tokens in the symboltable """
print(" *** Symbol Table ***")
for name in symtbl.keys(): # keys is a list of the names (printable form of tokens)
tok = symtbl[name]
if tok.token == idsym:
printToken(tok)
#===============================================================================
def getch():
#===============================================================================
global line
global charIndex
global linenumber
while True:
if charIndex < len(line): # See if used up current line
ch = line[charIndex] # if not, get character
charIndex = charIndex + 1 # & move pointer for next time
else:
# line = f.readline()
# if line == "": line = EOF
print "#End of File"
print "#--> ",
line = raw_input() + "\n" # read new line, adding \n so it's like f.readline()
# line = srcfile.read()
charIndex = 0 # & reset character pointer
linenumber = linenumber + 1
continue
if ch == "\n":
ch = " "
if ch == '?':
dumpSymTbl()
continue
return ch
#===============================================================================
def ungetch():
#===============================================================================
""" Unget the next character peeked at when building variables, numbers
and when distinguishing between >= and > ...
"""
global charIndex;
charIndex = charIndex - 1;
#===============================================================================
def getoken():
#===============================================================================
""" GETOKEN - Put next token into the global TOKEN """
global token
global i
global m
global counterafter
global counterafter1
x = 0
ch = getch() # skip whitespace
while ch in ["\t", " ", "\n"]:
ch = getch()
# If ch is alphabetic then this is start of reserved word or an identifier
if ch.isalpha(): # Letter therefore it's either identifier or reserved word
name = ""
while ch.isalpha() or ch.isdigit() or ch == "_":
name = name + ch
ch = getch()
ungetch() # let terminator be used next time
token = lookup(name) # See if token's known
if token is None: # if not
token = addToSymTbl(name, idsym) # add as 'idsym'-IDENTIFIER
return # we've set token.token to either id or tokentype of reserved word
elif ch in ["{", "}", "(", ")", "[", "]", "+", "-", "*", "/", ";", ",", ":", EOF]:
token = lookup(ch) # preloaded with appropriate token
elif ch.isdigit():
# In the real version, build number and don't forget to end with ungetch()
while(ch.isdigit() == True):
x = str(x) + str(ch)
ch = getch()
ch = ungetch()
token = symbol(x, number, value=int(x)) # simplistic SINGLE DIGIT Ascii to Binary
return
# elif ch == "-":
# x = ""
# no =""
# ch = getch()
# if ch.isdigit() ==True:
# while ch.isdigit():
# x = str(x) + str(ch)
# ch = getch()
#
# ch = ungetch()
#
# no = "-" + str(x)
#
# token = symbol(no, number, value = int(no))
elif ch == '#':
str1 = ""
ch = getch()
while(ch != " "):
str1 = str(str1) + str(ch)
ch = getch()
ch = getch()
token = symbol(str1, commentstr, value=str(str1)) # simplistic SINGLE DIGIT Ascii to Binary
print("#comment: " + str(str1))
return
elif ch == '"':
a = ""
ch = getch()
counterafter1 =counterafter
i=counterafter
if counterafter != 100:
counterafter=counterafter+4;
counterafter = i
while (ch != '"'):
a = str(a) + str(ch)
if ch != " ":
b = "'"+ch+"'"
emit(i, "constant",b)
ch = getch()
i=i+1
emit(i, "constant", 13)
emit(i+1, "constant", 0)
# emit(i+2, "writech", '')
emit(i+2, "return", '')
ch = getch()
counterafter=i+3
token = symbol(a, stringsym, value=str(a)) # simplistic SINGLE DIGIT Ascii to Binary
# printMsg()
return
elif ch == "<":
ch = getch()
if ch == "=":
lt = ""
lt = "<" + "="
token = symbol(lt, lessthanequal, value=str(lt)) # simplistic SINGLE DIGIT Ascii to Binary
return
else:
ch == ungetch()
token = symbol("<", lessthan, value="<") # simplistic SINGLE DIGIT Ascii to Binary
return
elif ch == "!":
ne = ""
ch = getch()
if ch == "=":
ne = "!" + "="
token = symbol(ne, jumpne, value=str(ne)) # simplistic SINGLE DIGIT Ascii to Binary
return
else:
ch == ungetch()
token = symbol("!", NOT , value="!") # simplistic SINGLE DIGIT Ascii to Binary
return
elif ch == "=":
eq = ""
ch = getch()
if ch == "=":
eq = "=" + "="
token = symbol(eq, jumpeq, value=str(eq)) # simplistic SINGLE DIGIT Ascii to Binary
return
else:
ch == ungetch()
token = symbol("=", assignsym, value="=") # simplistic SINGLE DIGIT Ascii to Binary
return
elif ch == ">":
gt = ""
ch = getch()
if ch == "=":
gt = ">" + "="
token = symbol(gt, lessthanequal, value=str(gt)) # simplistic SINGLE DIGIT Ascii to Binary
return
else:
ch == ungetch()
token = symbol(">", greaterthan, value=">") # simplistic SINGLE DIGIT Ascii to Binary
return
else:
print "Unknown character -->%s<- decimal %d" % (ch, ord(ch))
sys.exit(1) # Abort Compilation
#======================================================================
# THE GRAMMAR
# <program> ::= { <id> ; <vars > <stmtlist> }
# <vars> ::= var { <id> ; } % DECLARATIONS
# <array> ::= [<expr>]
# <stmtlist> ::= <stmt> { ; <stmt> }
# <stmt> ::= print <id>
# <id> = <expr>
# <expr> ::= <factor> { (+ | - | * | /) <factor> } % No precedence
# <factor> ::= [+/-] ID | Number
#======================================================================
# Centralised Parser Error Message handler
#======================================================================
#===============================================================================
def error (msg):
#===============================================================================
print line
print "-" * charIndex, "^"
print("Error on %d - %s\n" % (number, msg))
printToken(token)
print("\n")
#===============================================================================
def emit (memadr, opcode, parameter):
#===============================================================================
"""EMIT CODE - Emit a of code with a Parameter
if first arg is zero - (the memory address), use and incr CODEPTR"""
global codeptr
if (memadr == 0):
memadr = codeptr
codeptr = codeptr + 1
print "%6d %-8s %-7s" % (memadr, opcode, parameter)
#======================================================================
# VARIABLE DECLARATIONS
# <vars> ::= V { <id> ; }
#===============================================================================
def vars() :
#===============================================================================
ta = 0
tn = []
global varptr;
getoken();
if token.token == idsym:
ta = token.address
tn = token.name
getoken()
if token.token == leftsquarebrace:
getoken()
if token.token == number:
# emit(0, "loadv",token.value)
# emit(0, "store", token.value+300)
array()
if token.token == rightsquarebrace:
getoken()
else:
error("var error: ] expected - 1")
else:
getoken()
elif tn == "i":
# print("#The array name is " + str(tn)+"\n")
if token.token == rightsquarebrace:
getoken()
else:
if ta != 0:
print("%c already declared\n", tn);
#assignStmt()
else:
symtbl[tn].address = varptr;
varptr = varptr + 1
# emit(0, "load", varptr)
if token.token == assignsym:
getoken()
expression()
if token.token == rightbracket:
getoken()
if token.token == comma:
vars()
elif token.token == semicolon : getoken()
else: error("comma or semicolon expected in declaration")
#===============================================================================
def array():
#===============================================================================
global array;
# getoken()
while (token.token == number):
print("#array address")
emit(0, "store", token.value + 400)
print("#array value " +str(token.value))
getoken();
#======================================================================
# STMTLIST
# <stmtlist> ::= <stmt> { ; <stmt> }
#===============================================================================
def stmtList():
#===============================================================================
stmt()
while (token.token != rightbrace):
stmt()
#======================================================================
# STMT
#===============================================================================
def stmt():
#===============================================================================
""" <stmt> ::= print <expression|string>| read <vars> | <id> = <expression> |
if <condition> <stmt> [else <stmt>]| while <condition> <stmt>|
<stmtList> | do <stmsList> forever | break | continue
"""
global codeptr
thisStmtAdr = codeptr # Jump DEMO - not part of Stmt
# if token.token == arraysym:
# array()
if token.token == printsym:
printStmt()
elif token.token == readsym:
readStmt()
elif token.token == number:
expression()
elif token.token == idsym:
assignStmt()
elif token.token == ifsym:
ifStmt()
elif token.token == elsesym:
elseStmt()
elif token.token == whilesym:
whileStmt()
elif token.token == dosym:
doStmt()
elif token.token == returnsym:
expression()
elif token.token == continuesym:
continueStmt()
elif token.token == leftbracket:
getoken()
elif token.token == leftbrace:
getoken()
elif token.token == stringsym:
# print(str(token.name))
printMsg()
getoken()
elif token.token == assignsym:
getoken()
elif token.token == commentstr:
# print(str(token.name))
getoken()
elif token.token == breaksym:
getoken()
elif token.token == lessthanequal:
getoken()
elif token.token == greaterthanequal:
getoken()
elif token.token == jumpeq:
getoken()
elif token.token == jumpne:
getoken()
elif token.token == rightbracket:
getoken()
elif token.token == semicolon:
getoken()
elif token.token == comma:
getoken()
elif token.token == rightsquarebrace:
getoken()
elif token.token == rightbrace:
getoken()
else:
error("Expected start of a statement")
# emit (0, "return", thisStmtAdr) Jump DEMO need in break program
#===============================================================================
def printStmt():
#===============================================================================
""" <printStmt> ::= print <expression|string>"""
getoken()# skip "print"
stmt()
emit(0, "load", 501)
expression()
emit(0, "writeint", 502)
# printMsg()
# emit(0, "writeint", 502)
# if token.token == rightbrace: getoken()
# print("\n*** Compilation finished ***\n")
#===============================================================================
def printMsg():
#===============================================================================
""" <printMsg> ::= printMsg <expression>"""
# print("#"+str(counterafter)+ " counterafter")
# print("#"+str(counterafter1)+ " counterafter1")
# if counterafter != 100:
# emit(0,"loadv",counterafter )
emit(0, "loadv", counterafter1)
emit(0, "store", 1)
emit(0, "call", 40)
emit(40, "load-Ind", 0)
emit(41, "jumpeq", 45)
emit(42, "writech",0)
emit(43, "increment", 1)
emit(44, "jump", 40)
emit(45, "return", '')
getoken()
#===============================================================================
def readStmt():
#===============================================================================
""" <readStmt> ::= read <vars>"""
getoken()
emit(0, "readint", 7)
emit(0, "store", 502)
writeStmt()
#===============================================================================
def writeStmt():
#===============================================================================
""" <readStmt> ::= read <vars>"""
getoken()
emit(0,"load", 501)
emit(0, "writeint", 501)
#===============================================================================
def assignStmt():
#===============================================================================
"""
<id> = <expression>
"""
whichidentifier = token # Remember which ID on Left
getoken() # Get token after identifier
if token.token == assignsym:
getoken()
elif token.token == leftsquarebrace:
vars()
elif token.token == leftbrace:
vars()
elif token.token == jumpeq:
getoken()
elif token.token == jumpne:
getoken()
elif token.token == rightbracket:
getoken()
elif token.token == lessthanequal:
getoken()
elif token.token == comma:
getoken()
elif token.token == greaterthanequal:
getoken()
# elif token.token == idsym: factor()
else:
error("Expected = in assignment statement")
expression()
# Save result into LHS runtime address
#===============================================================================
def ifStmt():
# if-then-else
#===============================================================================
""" <ifStmt> ::= if <expression>"""
print("#IFSmt")
getoken() # skip "if"
expression()
stmt()
expression()
#===============================================================================
def elseStmt():
# if-then-else
#===============================================================================
""" <elseStmt> ::= else <expression>"""
print("#elseSmt")
getoken()
stmt()
expression()
emit(314, "jump", 22)
#===============================================================================
def whileStmt():
#===============================================================================
""" <whileStmt> ::= while (condition)statement"""
# emit(0, "load", 201)
emit(0, "store", 502)
getoken()
expression() # num>0
# emit(0, "jump", 22)
stmt()
#===============================================================================
def expression():
#===============================================================================
"""
Leaves result in ACC at runtime
Use addresses 999 & 998 as Temporary variables
<expression> ::= <factor> { (+ | -) <factor> }
"""
if token.token == leftbracket: getoken()
factor()
## 1st start==============================================================================
while token.token == plus or token.token == minus or token.token == mpy or token.token == div or token.token == lessthan or token.token == greaterthan or token.token == lessthanequal or token.token == greaterthanequal or token.token == jumpne or token.token == jumpeq:
op = token # remember -
getoken() # skip past -
# emit(0, "store", 997) # Save current result
factor()
if op.token == plus:
emit(0, "add", 502)
emit(0, "store", 502)
# emit(0, "jump", 22)
# if op.token == leftbracket:getoken()
if op.token == minus:
## 2nd start==============================================================================
if token.token == plus or token.token == minus or token.token == mpy or token.token == div:
op2 = token# remember *
getoken() # skip past *
factor()
if op2.token == plus: # Subtract - have to swap operand order
emit(0, "load", 210)
emit(0, "add", 203)
emit(0, "store", 500)
if op2.token == minus: # Subtract - have to swap operand order
emit(0, "load", 501)
emit(0, "subtract", 201)
emit(0, "store", 501)
if op2.token == mpy:
## 3rd start==============================================================================
while token.token == plus or token.token == minus or token.token == mpy or token.token == div:
op3 = token# remember *
getoken() # skip past *
factor()
if op3.token == plus: # Subtract - have to swap operand order
emit(0, "load", 210)
emit(0, "add", 203)
emit(0, "store", 500)
if op3.token == minus: # Subtract - have to swap operand order
emit(0, "load", 501)
emit(0, "subtract", 210)
emit(0, "store", 501)
if op3.token == mpy:
factor()
## 4th start==============================================================================
while token.token == plus or token.token == minus or token.token == mpy or token.token == div:
if token.token == plus:
op4 = token# remember +
getoken() # skip past +
factor()
if op4.token == plus: # Subtract - have to swap operand order
emit(0, "load", 210)
emit(0, "add", 203)
emit(0, "store", 500)
if token.token == minus:
op4 = token# remember -
getoken() # skip past -
factor()
if op4.token == minus: # Subtract - have to swap operand order
emit(0, "load", 210)
emit(0, "subtract", 203)
emit(0, "store", 500)
if token.token == mpy:
op4 = token
getoken()
factor()
if op4.token == mpy: # Subtract - have to swap operand order
emit(0, "load", 210)
emit(0, "mpy", 203)
emit(0, "store", 500)
if token.token == div:
op4 = token
getoken()
factor()
if op4.token == div: # Subtract - have to swap operand order
emit(0, "load", 210)
emit(0, "div", 203)
emit(0, "store", 500)
## 4th end==============================================================================
emit(0, "mpy", 205)
emit(0, "store", 501)
## 3rd end==============================================================================
emit(0, "mpy", 210)
emit(0, "store", 501)
## 2nd end==============================================================================
else:
emit(0, "load", 501)
emit(0, "subtract", 201)
emit(0, "store", 501)
emit(0, "jump", 24)
elif op.token == mpy:
emit(0, "load", 206)
emit(0, "mpy", 7)
emit(0, "store", 502)
elif op.token == minus: # Subtract - have to swap operand order
emit(0, "load", 590)
emit(0, "subtract", 201)
emit(0, "store", 501)
emit(0, "writeInt", 502)
elif op.token == div:
emit(0, "load", 502)
emit(0, "div", 202)
emit(0, "store", 7)
elif op.token == lessthan:
emit(0, "load", 501)
emit(0, "compare", 212)
emit(0, "jumplt", 300)
emit(300, "writeInt", 502)
elif op.token == greaterthan:
emit(0, "load", 208)
emit(0, "compare", 7)
emit(0, "jumpgt", 50)
emit(50, "halt", '') # less than 2 go to else
elif op.token == lessthanequal:
emit(0, "load", 501)
emit(0, "compare", 212)
emit(0, "jumplt", 300)
emit(300, "writeInt", 502)
elif op.token == greaterthanequal:
emit(0, "load", 501)
emit(0, "compare", 212)
emit(0, "jumpgt", 300)
emit(300, "writeInt", 502)
elif op.token == jumpne:
emit(0, "load", 205)
emit(0, "compare", 502)
emit(0, "jumpne", 310)
emit(0, "writeInt", 0)
emit(0, "halt", 0)
emit(310, "writeInt", 502)
elif op.token == jumpeq:
emit(0, "load", 501)
emit(0, "compare", 200)
emit(0, "jumpeq", 300)
# emit(0, "halt", 0)
emit(300, "writeInt", 502)
emit(301, "jump",30)
#===============================================================================
def factor():
#===============================================================================
"""
# FACTOR() - leaves result in ACC at runtime
<factor> ::= identifier | number
"""
if token.token == plus:
getoken()
# - (unary)
elif token.token == minus:
getoken()
if token.token == idsym:
emit(0, "load", token.address)
getoken()
elif token.token == stringsym: #################
print("#String: " + str(token.name))
printMsg()
getoken()
elif token.token == number:
emit(0, "loadv", token.value)
emit(0, "store", 200 + token.value)
getoken()
elif token.token == commentstr:
print ("#Comment: " + str(token.name))
getoken()
# elif token.token == assignsym:
# getoken()
elif token.token == leftbracket:
getoken()
# print "this is token",tokenNames[token.token]
elif token.token == leftsquarebrace: getoken()
elif token.token == rightbracket:
getoken()
elif token.token == breaksym:
emit(0,"halt", 0)
elif token.token == lessthanequal:
getoken()
elif token.token == greaterthanequal:
getoken()
elif token.token == jumpeq:
getoken()
elif token.token == rightsquarebrace:
getoken()
elif token.token == semicolon:
getoken()
elif token.token == comma:
getoken()
elif token.token == leftbrace:
getoken()
elif token.token == rightbrace:
print("")
elif token.token == ifsym:
ifStmt()
elif token.token == printsym:
getoken()
else:
error("Start Of Factor Expected")
#===============================================================================
def function():
#===============================================================================
if token.token == functionsym:
getoken()
if token.token == idsym:
getoken()
if token.token == varsym :
vars()
if token.token == declaresym :
vars()
if token.token == varsym :
vars()
if token.token == leftbrace:
vars()
stmtList()
stmtList()
if token.token == rightbrace:
print "#---Function Finished---"
#===============================================================================
def program():
#===============================================================================
if token.token == leftbrace:
getoken()
if token.token == programsym:
getoken()
# else: error("Program start with 'program' keyword")
if token.token == idsym:
getoken()
# else: error("Program name expected")
if token.token == semicolon:
getoken()
# else: error("Semicolon expected")
if token.token == declaresym :
vars()
if token.token == varsym :
vars()
if token.token == functionsym:
function()
if token.token == leftbrace:
getoken()
stmtList()
stmtList()
if token.token == rightbrace:
print "#***Compilation Finished****"
#======================================================================
def main():
#======================================================================
global line
global srcfile
global charIndex
initSymTbl()
with open("test.txt") as srcfile:
# out1file = open('output.obj','w')
line = srcfile.read()
# out1file.write("hello")
# print line
charIndex = 0
debugScanner = False
if debugScanner: # Scanner Test Routine - Read a line and display the tokens
getoken()
while token.token is not None: # Skeleton for testing Scanner
printToken(token)
# y = str(token)
# out1file.write(y)
getoken()
sys.exit(1)
else:
getoken() # Parse Program according to the grammar
program()
#===============================================================================
# Main Compiler starts here
#===============================================================================
print "#Microcompiler.py v0.2"
emit(0, "load", 9)
main()
# emit(0, "constant", "'A'") #need in break,comment,exitloop,writer-if-read-write-ch program
# emit(0, "constant", 10)
# emit(0, "constant", 12)
# emit(0, "constant", 25)
# emit(0, "constant", -10)
"""
srcfile = open('tiny_1.txt', 'r')
lexer = shlex.shlex(srcfile)
for token in lexer:
print repr(token)
"""
# getoken()
#=======================================================================
# *** That's it folks - written by Giovanni Moretti - April 27, 2011 ***
#=======================================================================
| [
[
1,
0,
0.0009,
0.0009,
0,
0.66,
0,
540,
0,
1,
0,
0,
540,
0,
0
],
[
14,
0,
0.0027,
0.0009,
0,
0.66,
0.02,
777,
1,
0,
0,
0,
0,
3,
0
],
[
8,
0,
0.0112,
0.0108,
0,
0.6... | [
"import re",
"__author__ = 'YeeHin Kwok'",
"\"\"\" Giovanni's MicroCompiler Demo\n\n<program> ::= { <id> ; <vars > <stmtlist> }\n<vars> ::= V { <id> ; } % DECLARATIONS\n\n<stmtlist> ::= <stmt> { ; <stmt> }\n<stmt> ::= P <id> | <id> = <expr>",... |
import re
__author__ = 'YeeHin Kwok'
""" Giovanni's MicroCompiler Demo
<program> ::= { <id> ; <vars > <stmtlist> }
<vars> ::= V { <id> ; } % DECLARATIONS
<stmtlist> ::= <stmt> { ; <stmt> }
<stmt> ::= P <id> | <id> = <expr>
<expr> ::= <factor> { (+ | -) <factor> } % No precedence
<factor> ::= ID | Number
"""
import sys
import shlex
#===============================================================================
# # Lexical Analyser - the "Scanner" - Define the TokenTypes
#===============================================================================
tokenNames = \
[ "unknownToken", "idsym", "assignsym", "leftbrace", "rightbrace",
"varsym", "semicolon", "whilesym", "leftbracket", "rightbracket",
"printsym", "ifsym", "equals", "lessthan", "greaterthan",
"number", "plus", "minus", "mpy", "div", "elsesym", "declaresym", "forsym", "andsym", "elifsym", "dosym", "returnsym", "notsym",
"continuesym", "breaksym", "nonesym", "programsym", "functionsym", "leftsquarebrace", "rightsquarebrace",
"lessthanequal", "colon", "comma", "comment", "commentstr", "dot", " greaterthanequal", "jumpeq", "jumpne",
"andop", "orop", "quote ", "stringsym", "arraysym", "readsym", "endfile"]
# define the tokens as variables
unknownToken, idsym, assignsym, leftbrace, rightbrace, \
varsym, semicolon, whilesym, leftbracket, rightbracket, \
printsym, ifsym, equals, lessthan, greaterthan, \
number, plus, minus, mpy, div, elsesym, declaresym, forsym, andsym, elifsym, dosym, returnsym, notsym, \
continuesym, breaksym, nonesym, programsym, functionsym, leftsquarebrace, rightsquarebrace, \
lessthanequal, colon, comma, comment, commentstr, dot, greaterthanequal, jumpeq, jumpne, \
andop, orop, quote, stringsym, arraysym, readsym, endfile = range(0, len(tokenNames))
#===============================================================================
class symbol:
#===============================================================================
name = None # String representation
token = None; # Corresponding token
address = 0; # For variables, their runtime address
value = None # on defined for numbers
def __init__(self, name, token, value=0):
self.name = name
self.token = token
self.address = 0 # for identifiers, their address
self.value = value # for numbers, their value
symtbl = {}; # The Symbol Table, a dictionary of symbols indexed by name
#======================================================================
# GLOBALS for output of Lexical Analyser
# Set by each call to GeToken()
token = None; # A symbol
line = "\n" # the complex source file as a string
charIndex = 0 # the position in the source
linenumber = 0 # The current number
tokennum = 0
resultnum = 0
whichidentifier = None;
identifieraddress = 0;
i = 800
j = 800
counterafter = i
counterafter1 = j
EOF = chr(0)
#======================================================================
# Run Time Code Generation Variables
varptr = 500 # Arbitrary base address of memory for variables
codeptr = 10 # Address to output next instruction (for code)
#===============================================================================
# Symbol Table Management Routines
#===============================================================================
#===============================================================================
def addToSymTbl (name, token):
#===============================================================================
symtbl[name] = symbol(name, token) # Add a new symbol to the dictionary
return symtbl[name]
#===============================================================================
def lookup (thisName):
#===============================================================================
"# Find a given identifier in the Symbol Table, Return the symtbl entry"
if symtbl.has_key(thisName): # thisName has been seen before
return symtbl[thisName] # return the symtbl entry
else: return None
#===============================================================================
def initSymTbl():
#===============================================================================
"# Initialise Symbol Table, and preload reserved words"
addToSymTbl('var', varsym) # VAR
addToSymTbl('program', programsym)
addToSymTbl('function', functionsym)
addToSymTbl('while', whilesym) # WHILE
addToSymTbl('print', printsym) # PRINT
addToSymTbl('else', elsesym)
addToSymTbl('elif', elifsym)
addToSymTbl('if', ifsym)
addToSymTbl('declare', declaresym)
addToSymTbl('for', forsym)
addToSymTbl('None', nonesym)
addToSymTbl('continue', continuesym)
addToSymTbl('read', readsym) # READINT
addToSymTbl('do', dosym)
addToSymTbl('return', returnsym)
addToSymTbl('not', notsym)
# Now add symbols - NB only single character symbols are here
# multicharacter one like ">=" are still to do
addToSymTbl('=', assignsym)
addToSymTbl('#', comment)
addToSymTbl('<', lessthan)
addToSymTbl('>', greaterthan)
addToSymTbl('{', leftbrace)
addToSymTbl('}', rightbrace)
addToSymTbl('(', leftbracket)
addToSymTbl(')', rightbracket)
addToSymTbl('+', plus)
addToSymTbl('-', minus)
addToSymTbl(';', semicolon)
addToSymTbl('break', breaksym)
addToSymTbl('*', mpy)
addToSymTbl('/', div)
addToSymTbl('[', leftsquarebrace)
addToSymTbl(']', rightsquarebrace)
addToSymTbl(':', colon)
addToSymTbl(',', comma)
addToSymTbl('.', dot)
addToSymTbl('==', jumpeq)
addToSymTbl('!=', jumpne)
addToSymTbl('&&', andop)
addToSymTbl('||', orop)
addToSymTbl('"', quote)
addToSymTbl(EOF, endfile)
#===============================================================================
# Scanner Diagnostics
#===============================================================================
def printToken(tok):
#===============================================================================
" - display the specified token."
if tok.token == idsym:
print "Token = %10s, %-10s adr = %3d, val = %d" % \
(tokenNames[tok.token], tok.name, tok.address, tok.value)
elif tok.token == number:
print "Token = %10s %d" % (tokenNames[tok.token], tok.value)
else:
print "Token = %10s" % tokenNames[tok.token]
#==============================?=================================================
def dumpSymTbl():
#===============================================================================
""" Dump all the tokens in the symboltable """
print("# *** Symbol Table ***")
for name in symtbl.keys(): # keys is a list of the names (printable form of tokens)
tok = symtbl[name]
if tok.token == idsym:
print("#"),
printToken(tok)
#===============================================================================
def getch():
#===============================================================================
global line
global charIndex
global linenumber
while True:
if charIndex < len(line): # See if used up current line
ch = line[charIndex] # if not, get character
charIndex = charIndex + 1 # & move pointer for next time
else:
# line = f.readline()
# if line == "": line = EOF
dumpSymTbl()
print "#End of File"
print "#--> ",
line = raw_input() + "\n" # read new line, adding \n so it's like f.readline()
# line = srcfile.read()
charIndex = 0 # & reset character pointer
linenumber = linenumber + 1
continue
if ch == "\n":
ch = " "
if ch == '?':
dumpSymTbl()
continue
return ch
#===============================================================================
def ungetch():
#===============================================================================
""" Unget the next character peeked at when building variables, numbers
and when distinguishing between >= and > ...
"""
global charIndex;
charIndex = charIndex - 1;
#===============================================================================
def getoken():
#===============================================================================
""" GETOKEN - Put next token into the global TOKEN """
global token
global i
global m
global counterafter
global counterafter1
x = 0
ch = getch() # skip whitespace
while ch in ["\t", " ", "\n"]:
ch = getch()
# If ch is alphabetic then this is start of reserved word or an identifier
if ch.isalpha(): # Letter therefore it's either identifier or reserved word
name = ""
while ch.isalpha() or ch.isdigit() or ch == "_":
name = name + ch
ch = getch()
ungetch() # let terminator be used next time
token = lookup(name) # See if token's known
if token is None: # if not
token = addToSymTbl(name, idsym) # add as 'idsym'-IDENTIFIER
return # we've set token.token to either id or tokentype of reserved word
elif ch in ["{", "}", "(", ")", "[", "]", "+", "-", "*", "/", ";", ",", ":", EOF]:
token = lookup(ch) # preloaded with appropriate token
elif ch.isdigit():
# In the real version, build number and don't forget to end with ungetch()
while(ch.isdigit() == True):
x = str(x) + str(ch)
ch = getch()
ch = ungetch()
token = symbol(x, number, value=int(x)) # simplistic SINGLE DIGIT Ascii to Binary
return
# elif ch == "-":
# x = ""
# no =""
# ch = getch()
# if ch.isdigit() ==True:
# while ch.isdigit():
# x = str(x) + str(ch)
# ch = getch()
#
# ch = ungetch()
#
# no = "-" + str(x)
#
# token = symbol(no, number, value = int(no))
elif ch == '#':
str1 = ""
ch = getch()
while(ch != " "):
str1 = str(str1) + str(ch)
ch = getch()
ch = getch()
token = symbol(str1, commentstr, value=str(str1)) # simplistic SINGLE DIGIT Ascii to Binary
print("#comment: " + str(str1))
return
elif ch == '"':
a = ""
ch = getch()
counterafter1 = counterafter
i = counterafter
if counterafter != 800:
counterafter = counterafter + 4;
counterafter = i
while (ch != '"'):
a = str(a) + str(ch)
if ch != " ":
b = "'"+ch+"'"
emit(i, "constant",b)
ch = getch()
else:
ch = getch()
i=i+1
emit(i, "constant", 13)
emit(i+1, "constant", 0)
# emit(i+2, "writech", '')
emit(i+2, "return", '')
ch = getch()
counterafter=i+3
token = symbol(a, stringsym, value=str(a)) # simplistic SINGLE DIGIT Ascii to Binary
# printMsg()
return
elif ch == "<":
ch = getch()
if ch == "=":
lt = ""
lt = "<" + "="
token = symbol(lt, lessthanequal, value=str(lt)) # simplistic SINGLE DIGIT Ascii to Binary
return
else:
ch == ungetch()
token = symbol("<", lessthan, value="<") # simplistic SINGLE DIGIT Ascii to Binary
return
elif ch == "!":
ne = ""
ch = getch()
if ch == "=":
ne = "!" + "="
token = symbol(ne, jumpne, value=str(ne)) # simplistic SINGLE DIGIT Ascii to Binary
return
else:
ch == ungetch()
token = symbol("!", NOT , value="!") # simplistic SINGLE DIGIT Ascii to Binary
return
elif ch == "=":
eq = ""
ch = getch()
if ch == "=":
eq = "=" + "="
token = symbol(eq, jumpeq, value=str(eq)) # simplistic SINGLE DIGIT Ascii to Binary
return
else:
ch == ungetch()
token = symbol("=", assignsym, value="=") # simplistic SINGLE DIGIT Ascii to Binary
return
elif ch == ">":
gt = ""
ch = getch()
if ch == "=":
gt = ">" + "="
token = symbol(gt, greaterthanequal, value=str(gt)) # simplistic SINGLE DIGIT Ascii to Binary
return
else:
ch == ungetch()
token = symbol(">", greaterthan, value=">") # simplistic SINGLE DIGIT Ascii to Binary
return
else:
print "Unknown character -->%s<- decimal %d" % (ch, ord(ch))
sys.exit(1) # Abort Compilation
#======================================================================
# THE GRAMMAR
# <program> ::= { <id> ; <vars > <stmtlist> }
# <vars> ::= var { <id> ; } % DECLARATIONS
# <array> ::= [<expr>]
# <stmtlist> ::= <stmt> { ; <stmt> }
# <stmt> ::= print <id>
# <id> = <expr>
# <expr> ::= <term> { (+ | - ) <term> }
# <term> ::= <factor> { (*|/) factor}
# <factor> ::= [+/-] ID | Number | expression
#======================================================================
# Centralised Parser Error Message handler
#======================================================================
#===============================================================================
def error (msg):
#===============================================================================
print line
print "-" * charIndex, "^"
print("Error on %d - %s\n" % (number, msg))
printToken(token)
print("\n")
#===============================================================================
def emit (memadr, opcode, parameter):
#===============================================================================
"""EMIT CODE - Emit a of code with a Parameter
if first arg is zero - (the memory address), use and incr CODEPTR"""
global codeptr
if (memadr == 0):
memadr = codeptr
codeptr = codeptr + 1
print "%6d %-8s %-7s" % (memadr, opcode, parameter)
#======================================================================
# VARIABLE DECLARATIONS
# <vars> ::= V { <id> ; }
# <vars> ::= <id>[array]
#===============================================================================
def vars() :
#===============================================================================
ta = 0
tn = []
global varptr;
getoken();
if token.token == idsym:
ta = token.address
tn = token.name
getoken()
if token.token == leftsquarebrace:
getoken()
if token.token == number: #number
print("#The address for "+ str(tn)+ " are ")
symtbl[tn].address = varptr;
emit(0, "constant", varptr)
while (token.value != 0):
# print("#address at " + str(varptr))
emit(0, "constant", token.value)
varptr = varptr + 1
token.value= token.value-1
array()
elif token.token == idsym: #id
# getoken()
expression()
getoken()
if token.token == rightsquarebrace:
getoken()
else:
if ta != 0:
print("#"),
print("%c already declared\n", tn);
# assignStmt()
else:
symtbl[tn].address = varptr;
varptr = varptr + 1
# emit(0, "load", varptr)
if token.token == assignsym:
getoken()
expression()
if token.token == number:
emit(0, "loadv", token.value)
emit(0, "add", 11)
emit(0, "store", 1)
getoken()
if token.token == rightbracket:
getoken()
if token.token == comma:
vars()
elif token.token == semicolon : getoken()
else: error("comma or semicolon expected in declaration")
#===============================================================================
def array():
# [expression]
#===============================================================================
global array;
expression()
#===============================================================================
def parameters():
#===============================================================================
vars()
if token.token == comma:
getoken()
vars()
#======================================================================
# STMTLIST
# <stmtlist> ::= <stmt> { ; <stmt> }
#===============================================================================
def stmtList():
#===============================================================================
stmt()
while (token.token != rightbrace):
stmt()
#======================================================================
# STMT
#===============================================================================
def stmt():
#===============================================================================
""" <stmt> ::= print <expression|string>| read <vars> | <id> = <expression> |
if <condition> <stmt> [else <stmt>]| while <condition> <stmt>|
<stmtList> | do <stmsList> forever | break | continue
"""
global codeptr
thisStmtAdr = codeptr # Jump DEMO - not part of Stmt
# if token.token == arraysym:
# array()
if token.token == vars:
expression()
if token.token == ifsym:
ifStmt()
if token.token == elsesym:
elseStmt()
elif token.token == whilesym:
whileStmt()
elif token.token == stmtList:
stmtList()
elif token.token == printsym:
printStmt()
elif token.token == readsym:
readStmt()
elif token.token == dosym:
doStmt()
elif token.token == breaksym:
factor()
elif token.token == continuesym:
continueStmt()
elif token.token == number:
expression()
elif token.token == idsym:
assignStmt()
elif token.token == functionsym:
function()
elif token.token == returnsym:
returnStmt()
elif token.token == stringsym:
# print(str(token.name))
printMsg()
getoken()
elif token.token == leftbracket or token.token == rightbracket or token.token == leftbrace or token.token == rightbrace or token.token == rightsquarebrace or token.token == assignsym:
getoken()
elif token.token == commentstr or token.token == breaksym:
# print(str(token.name))
getoken()
elif token.token == lessthan or token.token == greaterthan or token.token == lessthanequal or token.token == greaterthanequal or token.token == jumpeq or token.token == jumpne:
relational_op()
elif token.token == semicolon or token.token == comma:
getoken()
else:
error("Expected start of a statement")
# emit (0, "return", thisStmtAdr) Jump DEMO need in break program
#===============================================================================
def printStmt():
#===============================================================================
""" <printStmt> ::= print <expression|string>"""
global idaddress
getoken() # skip "print"
getoken()
if token.token == idsym:
print("#This is a id")
function()
emit(0, "writeint", 503)
if token.token == stringsym:
printMsg()
# emit(0, "writeint", 501)
if token.token == stringsym:
printMsg()
if token.token == idsym:
function()
emit(0, "writeint", 503)
getoken()
if token.token == idsym:
emit(0, "writeint", 501)
emit(0, "writeint", 502)
# emit(0, "halt", '')
getoken()
else:
emit(0, "writeint", 501)
getoken()
# emit(0, "writeint", 7)
#===============================================================================
def printMsg():
#===============================================================================
""" <printMsg> ::= printMsg <expression>"""
# print("#"+str(counterafter)+ " counterafter")
# print("#"+str(counterafter1)+ " counterafter1")
emit(0, "loadv", counterafter1)
emit(0, "store", 1)
emit(0, "call", 400)
emit(400, "load-Ind", 0)
emit(401, "jumpeq", 405)
emit(402, "writech", 0)
emit(403, "increment", 1)
emit(404, "jump", 400)
emit(405, "return", '')
getoken()
#===============================================================================
def readStmt():
#===============================================================================
""" <readStmt> ::= read <vars>"""
getoken()
emit(0, "readint", 7)
emit(0, "load", 7)
emit(0, "store", 500)
getoken()
#===============================================================================
def assignStmt():
#===============================================================================
"""
<id> = <expression>
"""
global tokennum
global resultnum
global whichidentifier
whichidentifier = token.name # Remember which ID on Left
whichidaddress = token.address
# print("#whichidentifier: " +str(whichidentifier))
getoken() # Get token after identifier
if token.token == assignsym:
getoken()
elif token.token == leftsquarebrace:
vars()
elif token.token == leftbrace:
vars()
elif token.token == jumpeq:
getoken()
elif token.token == jumpne:
getoken()
elif token.token == rightbracket:
getoken()
elif token.token == lessthanequal:
getoken()
elif token.token == idsym:
getoken()
elif token.token == leftbracket:
getoken()
elif token.token == comma:
getoken()
elif token.token == greaterthanequal:
getoken()
elif token.token == semicolon:
getoken()
else:
error("Expected = in assignment statement")
# print("#Store value")
expression()
passtoken = token.value
# print(str(tokennum))
symtbl[whichidentifier].value = tokennum
emit(0, "store", whichidaddress)
getoken()
#===============================================================================
def ifStmt():
# if-then-else
#===============================================================================
""" <ifStmt> ::= if <expression>"""
# print("#IFSmt")
getoken() # skip "if"
condition()
stmt()
#===============================================================================
def elseStmt():
# if-then-else
#===============================================================================
""" <elseStmt> ::= else <expression>"""
print("#ElseSmt")
# emit(200, "jump", 47) # less than 2 go to else
getoken()
stmt()
# emit(0, "halt", '')
#===============================================================================
def whileStmt():
#===============================================================================
""" <whileStmt> ::= while (condition)statement"""
# emit(0, "load", 201)
# emit(0, "store", 502)
getoken()
expression() # num>0
stmtList()
stmtList()
emit(0, "jump", 128)
#===============================================================================
def doStmt():
#===============================================================================
getoken()
expression()
stmt()
#===============================================================================
def returnStmt():
#===============================================================================
getoken()
if token.token == leftbracket:
getoken()
if token.token == idsym:
emit(600, "add", 505)
emit(601, "add", 1)
emit(602, "store", 503)
emit(603, "return", '')
if token.token == rightbracket:
getoken()
if token.token == semicolon:
getoken()
#===============================================================================
def condition():
#===============================================================================
if token.token == notsym:
emit(0, "Not", '')
getoken()
conditionalexp()
#===============================================================================
def conditionalexp():
#===============================================================================
expression()
relational_op()
expression()
#===============================================================================
def relational_op():
#===============================================================================
if token.token == lessthan or token.token == greaterthan or token.token == lessthanequal or token.token == greaterthanequal or token.token == jumpne or token.token == jumpeq:
op = token # remember -
getoken() # skip past -
term()
if op.token == lessthan:
# emit(0, "load", 501)
emit(0, "compare", 500)
emit(0, "jumplt", 43)
elif op.token == greaterthan:
emit(0, "load", 504)
emit(0, "compare", 1)
emit(0, "jumpgt", 123)
# emit(0, "jump", 123)
elif op.token == lessthanequal:
# emit(0, "load", 200)
emit(0, "compare", 500)
emit(0, "jumplt", 43)
emit(0, "jumpeq", 43)
# emit(300, "writeInt", 502)
elif op.token == greaterthanequal:
# emit(0, "load", 200)
emit(0, "compare", 500)
emit(0, "jumpgt", 43)
emit(0, "jumpeq", 43)
# emit(300, "writeInt", 502)
elif op.token == jumpne:
emit(0, "load", 205)
emit(0, "compare", 502)
emit(0, "jumpne", 310)
emit(0, "writeInt", 0)
emit(0, "halt", 0)
# emit(310, "writeInt", 502)
elif op.token == jumpeq:
# emit(0, "load", 200)
emit(0, "compare", 504)
emit(0, "jumpeq", 133)
emit(0, "jump", 138)
# emit(0, "halt", '')
# emit(0, "jump", 131)
#===============================================================================
def expression():
#===============================================================================
"""
Leaves result in ACC at runtime
Use addresses 999 & 998 as Temporary variables
<expression> ::= <factor> { (+ | -) <factor> } <- wrong
<expression> ::= <term> { (+ | -) <term> }
"""
global whichidentifier
global idaddress
global idvalue
if whichidentifier == None:
getoken()
else:
idaddress = symtbl[whichidentifier].address
idvalue = symtbl[whichidentifier].value
if token.token == leftbracket:
getoken()
term()
while token.token == plus or token.token == minus:
op = token # remember -
getoken() # skip past -
term()
if op.token == plus:
emit(0, "add", 501)
# emit(0, "store", 500)
# emit(0, "writeInt", 500)
elif op.token == minus: # Subtract - have to swap operand order
emit(0, "load", 501)
emit(0, "subtract", 1)
emit(0, "store", 501)
emit(0, "store", 1)
getoken()
term()
# print("term 1" + str(factor()))
## 1st start==============================================================================
while token.token == plus or token.token == minus:
op = token # remember -
getoken() # skip past -
# emit(0, "store", 997) # Save current result
term()
# print("term 2" + str(term))
# print("#whichidentifier " + whichidentifier)
if op.token == plus:
emit(0, "loadv", idvalue)
emit(0, "add", 1)
# emit(0, "store", idaddress)
# emit(0, "store", 500)
# emit(0, "writeInt", 500)
elif op.token == minus: # Subtract - have to swap operand order
emit(0, "load", 500)
emit(0, "subtract", 1)
emit(0, "store", idaddress)
emit(0, "store", 1)
# emit(0, "writeInt", 501)
#===============================================================================
def term():
#===============================================================================
"""
term::= factor {(*|/) factor}
"""
global idaddress
factor()
while token.token == mpy or token.token == div:
op = token # remember -
getoken() # skip past -
factor()
if op.token == mpy:
emit(0, "mpy", 1)
# emit(0, "store", 205)
emit(0, "store", 502)
emit(0, "store", 1)
while token.token == mpy:
op2 = token # remember -
getoken() # skip past -
factor()
emit(0, "mpy", 502)
# emit(0, "store", 205)
emit(0, "store", idaddress)
emit(0, "store", 1)
elif op.token == div:
# emit(0, "load", 502)
emit(0, "load",504)
emit(0, "div", 1)
#===============================================================================
def factor():
#===============================================================================
"""
# FACTOR() - leaves result in ACC at runtime
<factor> ::= [+|-] identifier | number | (expression)
"""
global tokennum
global whichidentifier
global idaddress
global idvalue
# [+|-] number
if token.token == plus:
getoken()
if token.token == number:
emit(0, "loadv", token.value)
emit(0, "store", 200 + token.value)
getoken()
# - (unary)
elif token.token == minus:
getoken()
if token.token == number:
emit(0, "loadv", 0 - token.value)
emit(0, "store", 200 + token.value)
getoken()
elif token.token == number:
emit(0, "loadv", token.value)
emit(0, "store", 1)
tokennum = token.value
getoken()
# identifier
elif token.token == idsym:
# print("#token address " + str(token.address))
# print("#token value " + str(token.value))
emit(0, "load", token.address)
getoken()
# (expression)
elif token.token == leftbracket:
expression()
elif token.token == lessthan or token.token == greaterthan or token.token == lessthanequal or token.token == greaterthanequal or token.token == jumpeq or token.token == jumpne:
relational_op()
# elif token.token == stringsym: #################
# print("#String: " + str(token.name))
# printMsg()
# printStmt()
# getoken()
elif token.token == commentstr or token.token == rightbracket or token.token == leftsquarebrace or token.token == rightsquarebrace:
# print ("#Comment: " + str(token.name))
getoken()
elif token.token == breaksym:
emit(0, "halt", '')
getoken()
elif token.token == semicolon or token.token == comma:
getoken()
elif token.token == leftbrace:
getoken()
elif token.token == rightbrace:
print("")
elif token.token == ifsym:
ifStmt()
elif token.token == printsym or token.token == returnsym or token.token == functionsym:
getoken()
else:
error("Start Of Factor Expected")
#===============================================================================
def function():
#===============================================================================
if token.token == functionsym:
getoken()
if token.token == idsym:
getoken()
if token.token == leftbracket:
getoken()
if token.token == idsym:
parameters()
elif token.token == number:
print("#"+str(token.value))
emit(0, "loadv", token.value)
emit(0, "store", 1)
getoken()
else:
error("Function error : No_parameter_input_for_function")
if token.token == comma:
getoken()
emit(0, "loadv", token.value)
emit(0, "call", 600)
getoken()
if token.token == rightbracket:
getoken()
if token.token == declaresym :
vars()
if token.token == varsym :
vars()
if token.token == semicolon:
getoken()
if token.token == leftbrace:
getoken()
if token.token == plus:
expression
getoken()
stmt()
# emit(0, "call", 600)
# returnStmt()
# emit(0, "call", 600)
if token.token == semicolon:
getoken()
if token.token == rightbrace:
print ("#---Function Finished---")
#===============================================================================
def program():
#===============================================================================
if token.token == leftbrace:
getoken()
if token.token == programsym:
getoken()
else: error("Program start with 'program' keyword")
if token.token == idsym:
getoken()
if token.token == semicolon:
getoken()
if token.token == declaresym :
vars()
if token.token == varsym :
vars()
if token.token == functionsym:
function()
if token.token == leftbrace:
getoken()
stmtList()
stmtList()
if token.token == rightbrace:
print "#***Compilation Finished****"
#======================================================================
def main():
#======================================================================
global line
global srcfile
global charIndex
initSymTbl()
with open("test.txt") as srcfile:
# out1file = open('output.obj','w')
line = srcfile.read()
# out1file.write("hello")
# print line
charIndex = 0
debugScanner = False
if debugScanner: # Scanner Test Routine - Read a line and display the tokens
getoken()
while token.token is not None: # Skeleton for testing Scanner
printToken(token)
# y = str(token)
# out1file.write(y)
getoken()
sys.exit(1)
else:
getoken() # Parse Program according to the grammar
program()
#===============================================================================
# Main Compiler starts here
#===============================================================================
print "#Microcompiler.py v0.2"
emit(0, "load", 9)
main()
"""
srcfile = open('tiny_1.txt', 'r')
lexer = shlex.shlex(srcfile)
for token in lexer:
print repr(token)
"""
# getoken()
#=======================================================================
# *** That's it folks - written by Giovanni Moretti - April 27, 2011 ***
#=======================================================================
| [
[
1,
0,
0.0008,
0.0008,
0,
0.66,
0,
540,
0,
1,
0,
0,
540,
0,
0
],
[
14,
0,
0.0024,
0.0008,
0,
0.66,
0.0167,
777,
1,
0,
0,
0,
0,
3,
0
],
[
8,
0,
0.0101,
0.0097,
0,
0... | [
"import re",
"__author__ = 'YeeHin Kwok'",
"\"\"\" Giovanni's MicroCompiler Demo\n\n<program> ::= { <id> ; <vars > <stmtlist> }\n<vars> ::= V { <id> ; } % DECLARATIONS\n\n<stmtlist> ::= <stmt> { ; <stmt> }\n<stmt> ::= P <id> | <id> = <expr>",... |
import re
__author__ = 'YeeHin Kwok'
""" Giovanni's MicroCompiler Demo
<program> ::= { <id> ; <vars > <stmtlist> }
<vars> ::= V { <id> ; } % DECLARATIONS
<stmtlist> ::= <stmt> { ; <stmt> }
<stmt> ::= P <id> | <id> = <expr>
<expr> ::= <factor> { (+ | -) <factor> } % No precedence
<factor> ::= ID | Number
"""
import sys
import shlex
#===============================================================================
# # Lexical Analyser - the "Scanner" - Define the TokenTypes
#===============================================================================
tokenNames = \
[ "unknownToken", "idsym", "assignsym", "leftbrace", "rightbrace",
"varsym", "semicolon", "whilesym", "leftbracket", "rightbracket",
"printsym", "ifsym", "equals", "lessthan", "greaterthan",
"number", "plus", "minus", "mpy", "div", "elsesym", "declaresym", "forsym", "andsym", "elifsym", "dosym", "returnsym", "notsym",
"continuesym", "breaksym", "nonesym", "programsym", "functionsym", "leftsquarebrace", "rightsquarebrace",
"lessthanequal", "colon", "comma", "comment", "commentstr", "dot", " greaterthanequal", "jumpeq", "jumpne",
"andop", "orop", "quote ", "stringsym", "arraysym", "readsym", "endfile"]
# define the tokens as variables
unknownToken, idsym, assignsym, leftbrace, rightbrace, \
varsym, semicolon, whilesym, leftbracket, rightbracket, \
printsym, ifsym, equals, lessthan, greaterthan, \
number, plus, minus, mpy, div, elsesym, declaresym, forsym, andsym, elifsym, dosym, returnsym, notsym, \
continuesym, breaksym, nonesym, programsym, functionsym, leftsquarebrace, rightsquarebrace, \
lessthanequal, colon, comma, comment, commentstr, dot, greaterthanequal, jumpeq, jumpne, \
andop, orop, quote, stringsym, arraysym, readsym, endfile = range(0, len(tokenNames))
#===============================================================================
class symbol:
#===============================================================================
name = None # String representation
token = None; # Corresponding token
address = 0; # For variables, their runtime address
value = None # on defined for numbers
def __init__(self, name, token, value=0):
self.name = name
self.token = token
self.address = 0 # for identifiers, their address
self.value = value # for numbers, their value
symtbl = {}; # The Symbol Table, a dictionary of symbols indexed by name
#======================================================================
# GLOBALS for output of Lexical Analyser
# Set by each call to GeToken()
token = None; # A symbol
line = "\n" # the complex source file as a string
charIndex = 0 # the position in the source
linenumber = 0 # The current number
tokennum = 0
resultnum = 0
whichidentifier = None;
identifieraddress = 0;
i = 100
j = 100
counterafter = i
counterafter1 = j
EOF = chr(0)
#======================================================================
# Run Time Code Generation Variables
varptr = 500 # Arbitrary base address of memory for variables
codeptr = 10 # Address to output next instruction (for code)
#===============================================================================
# Symbol Table Management Routines
#===============================================================================
#===============================================================================
def addToSymTbl (name, token):
#===============================================================================
symtbl[name] = symbol(name, token) # Add a new symbol to the dictionary
return symtbl[name]
#===============================================================================
def lookup (thisName):
#===============================================================================
"# Find a given identifier in the Symbol Table, Return the symtbl entry"
if symtbl.has_key(thisName): # thisName has been seen before
return symtbl[thisName] # return the symtbl entry
else: return None
#===============================================================================
def initSymTbl():
#===============================================================================
"# Initialise Symbol Table, and preload reserved words"
addToSymTbl('var', varsym) # VAR
addToSymTbl('program', programsym)
addToSymTbl('function', functionsym)
addToSymTbl('while', whilesym) # WHILE
addToSymTbl('print', printsym) # PRINT
addToSymTbl('else', elsesym)
addToSymTbl('elif', elifsym)
addToSymTbl('if', ifsym)
addToSymTbl('declare', declaresym)
addToSymTbl('for', forsym)
addToSymTbl('None', nonesym)
addToSymTbl('continue', continuesym)
addToSymTbl('read', readsym) # READINT
addToSymTbl('do', dosym)
addToSymTbl('return', returnsym)
addToSymTbl('not', notsym)
# Now add symbols - NB only single character symbols are here
# multicharacter one like ">=" are still to do
addToSymTbl('=', assignsym)
addToSymTbl('#', comment)
addToSymTbl('<', lessthan)
addToSymTbl('>', greaterthan)
addToSymTbl('{', leftbrace)
addToSymTbl('}', rightbrace)
addToSymTbl('(', leftbracket)
addToSymTbl(')', rightbracket)
addToSymTbl('+', plus)
addToSymTbl('-', minus)
addToSymTbl(';', semicolon)
addToSymTbl('break', breaksym)
addToSymTbl('*', mpy)
addToSymTbl('/', div)
addToSymTbl('[', leftsquarebrace)
addToSymTbl(']', rightsquarebrace)
addToSymTbl(':', colon)
addToSymTbl(',', comma)
addToSymTbl('.', dot)
addToSymTbl('==', jumpeq)
addToSymTbl('!=', jumpne)
addToSymTbl('&&', andop)
addToSymTbl('||', orop)
addToSymTbl('"', quote)
addToSymTbl(EOF, endfile)
#===============================================================================
# Scanner Diagnostics
#===============================================================================
def printToken(tok):
#===============================================================================
" - display the specified token."
if tok.token == idsym:
print "Token = %10s, %-10s adr = %3d, val = %d" % \
(tokenNames[tok.token], tok.name, tok.address, tok.value)
elif tok.token == number:
print "Token = %10s %d" % (tokenNames[tok.token], tok.value)
else:
print "Token = %10s" % tokenNames[tok.token]
#==============================?=================================================
def dumpSymTbl():
#===============================================================================
""" Dump all the tokens in the symboltable """
print("# *** Symbol Table ***")
for name in symtbl.keys(): # keys is a list of the names (printable form of tokens)
tok = symtbl[name]
if tok.token == idsym:
print("#"),
printToken(tok)
#===============================================================================
def getch():
#===============================================================================
global line
global charIndex
global linenumber
while True:
if charIndex < len(line): # See if used up current line
ch = line[charIndex] # if not, get character
charIndex = charIndex + 1 # & move pointer for next time
else:
# line = f.readline()
# if line == "": line = EOF
dumpSymTbl()
print "#End of File"
print "#--> ",
line = raw_input() + "\n" # read new line, adding \n so it's like f.readline()
# line = srcfile.read()
charIndex = 0 # & reset character pointer
linenumber = linenumber + 1
continue
if ch == "\n":
ch = " "
if ch == '?':
dumpSymTbl()
continue
return ch
#===============================================================================
def ungetch():
#===============================================================================
""" Unget the next character peeked at when building variables, numbers
and when distinguishing between >= and > ...
"""
global charIndex;
charIndex = charIndex - 1;
#===============================================================================
def getoken():
#===============================================================================
""" GETOKEN - Put next token into the global TOKEN """
global token
global i
global m
global counterafter
global counterafter1
x = 0
ch = getch() # skip whitespace
while ch in ["\t", " ", "\n"]:
ch = getch()
# If ch is alphabetic then this is start of reserved word or an identifier
if ch.isalpha(): # Letter therefore it's either identifier or reserved word
name = ""
while ch.isalpha() or ch.isdigit() or ch == "_":
name = name + ch
ch = getch()
ungetch() # let terminator be used next time
token = lookup(name) # See if token's known
if token is None: # if not
token = addToSymTbl(name, idsym) # add as 'idsym'-IDENTIFIER
return # we've set token.token to either id or tokentype of reserved word
elif ch in ["{", "}", "(", ")", "[", "]", "+", "-", "*", "/", ";", ",", ":", EOF]:
token = lookup(ch) # preloaded with appropriate token
elif ch.isdigit():
# In the real version, build number and don't forget to end with ungetch()
while(ch.isdigit() == True):
x = str(x) + str(ch)
ch = getch()
ch = ungetch()
token = symbol(x, number, value=int(x)) # simplistic SINGLE DIGIT Ascii to Binary
return
# elif ch == "-":
# x = ""
# no =""
# ch = getch()
# if ch.isdigit() ==True:
# while ch.isdigit():
# x = str(x) + str(ch)
# ch = getch()
#
# ch = ungetch()
#
# no = "-" + str(x)
#
# token = symbol(no, number, value = int(no))
elif ch == '#':
str1 = ""
ch = getch()
while(ch != " "):
str1 = str(str1) + str(ch)
ch = getch()
ch = getch()
token = symbol(str1, commentstr, value=str(str1)) # simplistic SINGLE DIGIT Ascii to Binary
print("#comment: " + str(str1))
return
elif ch == '"':
a = ""
ch = getch()
counterafter1 = counterafter
i = counterafter
if counterafter != 100:
counterafter = counterafter + 4;
counterafter = i
while (ch != '"'):
a = str(a) + str(ch)
if ch != " ":
b = "'" + ch + "'"
emit(i, "constant", b)
ch = getch()
i = i + 1
emit(i, "constant", 13)
emit(i + 1, "constant", 0)
emit(i + 2, "return", '')
ch = getch()
counterafter = i + 3
token = symbol(a, stringsym, value=str(a)) # simplistic SINGLE DIGIT Ascii to Binary
# printMsg()
return
elif ch == "<":
ch = getch()
if ch == "=":
lt = ""
lt = "<" + "="
token = symbol(lt, lessthanequal, value=str(lt)) # simplistic SINGLE DIGIT Ascii to Binary
return
else:
ch == ungetch()
token = symbol("<", lessthan, value="<") # simplistic SINGLE DIGIT Ascii to Binary
return
elif ch == "!":
ne = ""
ch = getch()
if ch == "=":
ne = "!" + "="
token = symbol(ne, jumpne, value=str(ne)) # simplistic SINGLE DIGIT Ascii to Binary
return
else:
ch == ungetch()
token = symbol("!", NOT , value="!") # simplistic SINGLE DIGIT Ascii to Binary
return
elif ch == "=":
eq = ""
ch = getch()
if ch == "=":
eq = "=" + "="
token = symbol(eq, jumpeq, value=str(eq)) # simplistic SINGLE DIGIT Ascii to Binary
return
else:
ch == ungetch()
token = symbol("=", assignsym, value="=") # simplistic SINGLE DIGIT Ascii to Binary
return
elif ch == ">":
gt = ""
ch = getch()
if ch == "=":
gt = ">" + "="
token = symbol(gt, greaterthanequal, value=str(gt)) # simplistic SINGLE DIGIT Ascii to Binary
return
else:
ch == ungetch()
token = symbol(">", greaterthan, value=">") # simplistic SINGLE DIGIT Ascii to Binary
return
else:
print "Unknown character -->%s<- decimal %d" % (ch, ord(ch))
sys.exit(1) # Abort Compilation
#======================================================================
# THE GRAMMAR
# <program> ::= { <id> ; <vars > <stmtlist> }
# <vars> ::= var { <id> ; } % DECLARATIONS
# <array> ::= [<expr>]
# <stmtlist> ::= <stmt> { ; <stmt> }
# <stmt> ::= print <id>
# <id> = <expr>
# <expr> ::= <term> { (+ | - ) <term> }
# <term> ::= <factor> { (*|/) factor}
# <factor> ::= [+/-] ID | Number | expression
#======================================================================
# Centralised Parser Error Message handler
#======================================================================
#===============================================================================
def error (msg):
#===============================================================================
print line
print "-" * charIndex, "^"
print("Error on %d - %s\n" % (number, msg))
printToken(token)
print("\n")
#===============================================================================
def emit (memadr, opcode, parameter):
#===============================================================================
"""EMIT CODE - Emit a of code with a Parameter
if first arg is zero - (the memory address), use and incr CODEPTR"""
global codeptr
if (memadr == 0):
memadr = codeptr
codeptr = codeptr + 1
print "%6d %-8s %-7s" % (memadr, opcode, parameter)
#======================================================================
# VARIABLE DECLARATIONS
# <vars> ::= V { <id> ; }
# <vars> ::= <id>[array]
#===============================================================================
def vars() :
#===============================================================================
ta = 0
tn = []
global varptr;
getoken();
if token.token == idsym:
ta = token.address
tn = token.name
getoken()
if token.token == leftsquarebrace:
getoken()
if token.token == number: #number
print("#The address for "+ str(tn)+ " are ")
symtbl[tn].address = varptr;
emit(0, "constant", varptr)
while (token.value != 0):
# print("#address at " + str(varptr))
emit(0, "constant", token.value)
varptr = varptr + 1
token.value= token.value-1
array()
elif token.token == idsym: #id
# getoken()
expression()
getoken()
if token.token == rightsquarebrace:
getoken()
else:
if ta != 0:
print("%c already declared\n", tn);
# assignStmt()
else:
symtbl[tn].address = varptr;
varptr = varptr + 1
# emit(0, "load", varptr)
if token.token == assignsym:
getoken()
expression()
if token.token == number:
emit(0, "loadv", token.value)
emit(0, "add", 11)
emit(0, "store", 1)
getoken()
if token.token == rightbracket:
getoken()
if token.token == comma:
vars()
elif token.token == semicolon : getoken()
else: error("comma or semicolon expected in declaration")
#===============================================================================
def array():
# [expression]
#===============================================================================
global array;
expression()
#===============================================================================
def parameters():
#===============================================================================
vars()
#======================================================================
# STMTLIST
# <stmtlist> ::= <stmt> { ; <stmt> }
#===============================================================================
def stmtList():
#===============================================================================
stmt()
while (token.token != rightbrace):
stmt()
#======================================================================
# STMT
#===============================================================================
def stmt():
#===============================================================================
""" <stmt> ::= print <expression|string>| read <vars> | <id> = <expression> |
if <condition> <stmt> [else <stmt>]| while <condition> <stmt>|
<stmtList> | do <stmsList> forever | break | continue
"""
global codeptr
thisStmtAdr = codeptr # Jump DEMO - not part of Stmt
# if token.token == arraysym:
# array()
if token.token == vars:
expression()
if token.token == ifsym:
ifStmt()
if token.token == elsesym:
elseStmt()
elif token.token == whilesym:
whileStmt()
elif token.token == stmtList:
stmtList()
elif token.token == printsym:
printStmt()
elif token.token == readsym:
readStmt()
elif token.token == dosym:
doStmt()
elif token.token == breaksym:
factor()
elif token.token == continuesym:
continueStmt()
elif token.token == number:
expression()
elif token.token == idsym:
assignStmt()
elif token.token == functionsym:
function()
elif token.token == returnsym:
returnStmt()
elif token.token == stringsym:
# print(str(token.name))
printMsg()
getoken()
elif token.token == leftbracket or token.token == rightbracket or token.token == leftbrace or token.token == rightbrace or token.token == rightsquarebrace or token.token == assignsym:
getoken()
elif token.token == commentstr or token.token == breaksym:
# print(str(token.name))
getoken()
elif token.token == lessthan or token.token == greaterthan or token.token == lessthanequal or token.token == greaterthanequal or token.token == jumpeq or token.token == jumpne:
relational_op()
elif token.token == semicolon or token.token == comma:
getoken()
else:
error("Expected start of a statement")
# emit (0, "return", thisStmtAdr) Jump DEMO need in break program
#===============================================================================
def printStmt():
#===============================================================================
""" <printStmt> ::= print <expression|string>"""
global idaddress
getoken() # skip "print"
getoken()
if token.token == idsym:
print("#This is a id")
function()
emit(0, "writeint", 503)
if token.token == stringsym:
printMsg()
# emit(0, "writeint", 501)
if token.token == stringsym:
printMsg()
if token.token == idsym:
function()
emit(0, "writeint", 503)
getoken()
if token.token == idsym:
emit(0, "writeint", 501)
emit(0, "writeint", 502)
# emit(0, "halt", '')
getoken()
else:
emit(0, "writeint", 501)
getoken()
# emit(0, "writeint", 7)
#===============================================================================
def printMsg():
#===============================================================================
""" <printMsg> ::= printMsg <expression>"""
# print("#"+str(counterafter)+ " counterafter")
# print("#"+str(counterafter1)+ " counterafter1")
emit(0, "loadv", counterafter1)
emit(0, "store", 1)
emit(0, "call", 400)
emit(400, "load-Ind", 0)
emit(401, "jumpeq", 405)
emit(402, "writech", 0)
emit(403, "increment", 1)
emit(404, "jump", 400)
emit(405, "return", '')
getoken()
#===============================================================================
def readStmt():
#===============================================================================
""" <readStmt> ::= read <vars>"""
getoken()
emit(0, "readint", 7)
emit(0, "load", 7)
emit(0, "store", 500)
getoken()
#===============================================================================
def assignStmt():
#===============================================================================
"""
<id> = <expression>
"""
global tokennum
global resultnum
global whichidentifier
whichidentifier = token.name # Remember which ID on Left
whichidaddress = token.address
# print("#whichidentifier: " +str(whichidentifier))
getoken() # Get token after identifier
if token.token == assignsym:
getoken()
elif token.token == leftsquarebrace:
vars()
elif token.token == leftbrace:
vars()
elif token.token == jumpeq:
getoken()
elif token.token == jumpne:
getoken()
elif token.token == rightbracket:
getoken()
elif token.token == lessthanequal:
getoken()
elif token.token == idsym:
getoken()
elif token.token == leftbracket:
getoken()
elif token.token == comma:
getoken()
elif token.token == greaterthanequal:
getoken()
elif token.token == semicolon:
getoken()
else:
error("Expected = in assignment statement")
# print("#Store value")
expression()
passtoken = token.value
# print(str(tokennum))
symtbl[whichidentifier].value = tokennum
emit(0, "store", whichidaddress)
getoken()
#===============================================================================
def ifStmt():
# if-then-else
#===============================================================================
""" <ifStmt> ::= if <expression>"""
print("#IFSmt")
getoken() # skip "if"
condition()
stmt()
#===============================================================================
def elseStmt():
# if-then-else
#===============================================================================
""" <elseStmt> ::= else <expression>"""
print("#ElseSmt")
# emit(200, "jump", 47) # less than 2 go to else
getoken()
stmt()
# emit(0, "halt", '')
#===============================================================================
def whileStmt():
#===============================================================================
""" <whileStmt> ::= while (condition)statement"""
# emit(0, "load", 201)
# emit(0, "store", 502)
getoken()
expression() # num>0
stmtList()
stmtList()
emit(0, "jump", 122)
#===============================================================================
def doStmt():
#===============================================================================
getoken()
expression()
stmt()
#===============================================================================
def returnStmt():
#===============================================================================
getoken()
if token.token == leftbracket:
getoken()
if token.token == idsym:
emit(600, "add", 505)
emit(601, "store", 503)
emit(602, "return", '')
if token.token == rightbracket:
getoken()
if token.token == semicolon:
getoken()
#===============================================================================
def condition():
#===============================================================================
if token.token == notsym:
emit(0, "Not", '')
getoken()
conditionalexp()
#===============================================================================
def conditionalexp():
#===============================================================================
expression()
relational_op()
expression()
#===============================================================================
def relational_op():
#===============================================================================
if token.token == lessthan or token.token == greaterthan or token.token == lessthanequal or token.token == greaterthanequal or token.token == jumpne or token.token == jumpeq:
op = token # remember -
getoken() # skip past -
term()
if op.token == lessthan:
# emit(0, "load", 501)
emit(0, "compare", 500)
emit(0, "jumplt", 43)
elif op.token == greaterthan:
# emit(0, "load", 200)
emit(0, "compare", 504)
emit(0, "jumpgt", 122)
emit(0, "jump", 130)
elif op.token == lessthanequal:
# emit(0, "load", 200)
emit(0, "compare", 500)
emit(0, "jumplt", 43)
emit(0, "jumpeq", 43)
# emit(300, "writeInt", 502)
elif op.token == greaterthanequal:
# emit(0, "load", 200)
emit(0, "compare", 500)
emit(0, "jumpgt", 43)
emit(0, "jumpeq", 43)
# emit(300, "writeInt", 502)
elif op.token == jumpne:
emit(0, "load", 205)
emit(0, "compare", 502)
emit(0, "jumpne", 310)
emit(0, "writeInt", 0)
emit(0, "halt", 0)
# emit(310, "writeInt", 502)
elif op.token == jumpeq:
# emit(0, "load", 200)
emit(0, "compare", 504)
emit(0, "jumpeq", 0)
# emit(0, "halt", '')
# emit(0, "jump", 131)
#===============================================================================
def expression():
#===============================================================================
"""
Leaves result in ACC at runtime
Use addresses 999 & 998 as Temporary variables
<expression> ::= <factor> { (+ | -) <factor> } <- wrong
<expression> ::= <term> { (+ | -) <term> }
"""
global whichidentifier
global idaddress
global idvalue
if whichidentifier == None:
getoken()
else:
idaddress = symtbl[whichidentifier].address
idvalue = symtbl[whichidentifier].value
if token.token == leftbracket:
getoken()
term()
while token.token == plus or token.token == minus:
op = token # remember -
getoken() # skip past -
term()
if op.token == plus:
emit(0, "add", 501)
# emit(0, "store", 500)
# emit(0, "writeInt", 500)
elif op.token == minus: # Subtract - have to swap operand order
emit(0, "load", 501)
emit(0, "subtract", 1)
emit(0, "store", 501)
emit(0, "store", 1)
getoken()
term()
# print("term 1" + str(factor()))
## 1st start==============================================================================
while token.token == plus or token.token == minus:
op = token # remember -
getoken() # skip past -
# emit(0, "store", 997) # Save current result
term()
# print("term 2" + str(term))
# print("#whichidentifier " + whichidentifier)
if op.token == plus:
emit(0, "loadv", idvalue)
emit(0, "add", 1)
# emit(0, "store", idaddress)
# emit(0, "store", 500)
# emit(0, "writeInt", 500)
elif op.token == minus: # Subtract - have to swap operand order
emit(0, "load", 500)
emit(0, "subtract", 1)
emit(0, "store", idaddress)
emit(0, "store", 1)
# emit(0, "writeInt", 501)
#===============================================================================
def term():
#===============================================================================
"""
term::= factor {(*|/) factor}
"""
global idaddress
factor()
while token.token == mpy or token.token == div:
op = token # remember -
getoken() # skip past -
factor()
if op.token == mpy:
emit(0, "mpy", 1)
# emit(0, "store", 205)
emit(0, "store", 502)
emit(0, "store", 1)
while token.token == mpy:
op2 = token # remember -
getoken() # skip past -
factor()
emit(0, "mpy", 502)
# emit(0, "store", 205)
emit(0, "store", idaddress)
emit(0, "store", 1)
elif op.token == div:
# emit(0, "load", 502)
emit(0, "div", 504)
#===============================================================================
def factor():
#===============================================================================
"""
# FACTOR() - leaves result in ACC at runtime
<factor> ::= [+|-] identifier | number | (expression)
"""
global tokennum
global whichidentifier
global idaddress
global idvalue
# [+|-] number
if token.token == plus:
getoken()
if token.token == number:
emit(0, "loadv", token.value)
emit(0, "store", 200 + token.value)
getoken()
# - (unary)
elif token.token == minus:
getoken()
if token.token == number:
emit(0, "loadv", 0 - token.value)
emit(0, "store", 200 + token.value)
getoken()
elif token.token == number:
emit(0, "loadv", token.value)
emit(0, "store", 1)
tokennum = token.value
getoken()
# identifier
elif token.token == idsym:
# print("#token address " + str(token.address))
# print("#token value " + str(token.value))
emit(0, "load", token.address)
getoken()
# (expression)
elif token.token == leftbracket:
expression()
elif token.token == lessthan or token.token == greaterthan or token.token == lessthanequal or token.token == greaterthanequal or token.token == jumpeq or token.token == jumpne:
relational_op()
elif token.token == stringsym: #################
print("#String: " + str(token.name))
# printMsg()
printStmt()
getoken()
elif token.token == commentstr or token.token == rightbracket or token.token == leftsquarebrace or token.token == rightsquarebrace:
# print ("#Comment: " + str(token.name))
getoken()
elif token.token == breaksym:
emit(0, "halt", '')
getoken()
elif token.token == semicolon or token.token == comma:
getoken()
elif token.token == leftbrace:
getoken()
elif token.token == rightbrace:
print("")
elif token.token == ifsym:
ifStmt()
elif token.token == printsym or token.token == returnsym or token.token == functionsym:
getoken()
else:
error("Start Of Factor Expected")
#===============================================================================
def function():
#===============================================================================
if token.token == functionsym:
getoken()
if token.token == idsym:
getoken()
if token.token == leftbracket:
getoken()
if token.token == idsym:
parameters()
elif token.token == number:
print("#"+str(token.value))
emit(0, "loadv", token.value)
emit(0, "call", 600)
getoken()
else:
error("Function error : No_parameter_input_for_function")
if token.token == rightbracket:
getoken()
if token.token == declaresym :
vars()
if token.token == varsym :
vars()
if token.token == semicolon:
getoken()
if token.token == leftbrace:
getoken()
if token.token == plus:
expression
getoken()
stmt()
# emit(0, "call", 600)
# returnStmt()
# emit(0, "call", 600)
if token.token == semicolon:
getoken()
if token.token == rightbrace:
print ("#---Function Finished---")
#===============================================================================
def program():
#===============================================================================
if token.token == leftbrace:
getoken()
if token.token == programsym:
getoken()
else: error("Program start with 'program' keyword")
if token.token == idsym:
getoken()
if token.token == semicolon:
getoken()
if token.token == declaresym :
vars()
if token.token == varsym :
vars()
if token.token == functionsym:
function()
if token.token == leftbrace:
getoken()
stmtList()
stmtList()
if token.token == rightbrace:
print "#***Compilation Finished****"
#======================================================================
def main():
#======================================================================
global line
global srcfile
global charIndex
initSymTbl()
with open("test.txt") as srcfile:
# out1file = open('output.obj','w')
line = srcfile.read()
# out1file.write("hello")
# print line
charIndex = 0
debugScanner = False
if debugScanner: # Scanner Test Routine - Read a line and display the tokens
getoken()
while token.token is not None: # Skeleton for testing Scanner
printToken(token)
# y = str(token)
# out1file.write(y)
getoken()
sys.exit(1)
else:
getoken() # Parse Program according to the grammar
program()
#===============================================================================
# Main Compiler starts here
#===============================================================================
print "#Microcompiler.py v0.2"
emit(0, "load", 9)
main()
"""
srcfile = open('tiny_1.txt', 'r')
lexer = shlex.shlex(srcfile)
for token in lexer:
print repr(token)
"""
# getoken()
#=======================================================================
# *** That's it folks - written by Giovanni Moretti - April 27, 2011 ***
#=======================================================================
| [
[
1,
0,
0.0008,
0.0008,
0,
0.66,
0,
540,
0,
1,
0,
0,
540,
0,
0
],
[
14,
0,
0.0025,
0.0008,
0,
0.66,
0.0167,
777,
1,
0,
0,
0,
0,
3,
0
],
[
8,
0,
0.0103,
0.0099,
0,
0... | [
"import re",
"__author__ = 'YeeHin Kwok'",
"\"\"\" Giovanni's MicroCompiler Demo\n\n<program> ::= { <id> ; <vars > <stmtlist> }\n<vars> ::= V { <id> ; } % DECLARATIONS\n\n<stmtlist> ::= <stmt> { ; <stmt> }\n<stmt> ::= P <id> | <id> = <expr>",... |
import re
__author__ = 'YeeHin Kwok'
""" Giovanni's MicroCompiler Demo
<program> ::= { <id> ; <vars > <stmtlist> }
<vars> ::= V { <id> ; } % DECLARATIONS
<stmtlist> ::= <stmt> { ; <stmt> }
<stmt> ::= P <id> | <id> = <expr>
<expr> ::= <factor> { (+ | -) <factor> } % No precedence
<factor> ::= ID | Number
"""
import sys
import shlex
#===============================================================================
# # Lexical Analyser - the "Scanner" - Define the TokenTypes
#===============================================================================
tokenNames =\
[ "unknownToken", "idsym", "assignsym", "leftbrace", "rightbrace",
"varsym", "semicolon", "whilesym", "leftbracket", "rightbracket",
"printsym", "ifsym", "equals", "lessthan", "greaterthan",
"number", "plus", "minus","mpy","div","elsesym","declaresym","forsym","andsym","elifsym","dosym",
"continuesym","breaksym","nonesym","programsym","leftsquarebrace","rightsquarebrace",
"lessthanequal","colon","comma","comment","commentstr","dot"," greaterthanequal","jumpeq","jumpne",
"andop","orop","quote ","stringsym","arraysym","readsym","endfile"]
# define the tokens as variables
unknownToken, idsym, assignsym, leftbrace, rightbrace,\
varsym, semicolon, whilesym, leftbracket, rightbracket,\
printsym, ifsym, equals, lessthan, greaterthan,\
number, plus, minus, mpy,div,elsesym,declaresym,forsym,andsym,elifsym,dosym,\
continuesym,breaksym,nonesym,programsym,leftsquarebrace,rightsquarebrace,\
lessthanequal,colon,comma,comment,commentstr,dot, greaterthanequal,jumpeq,jumpne,\
andop,orop,quote,stringsym,arraysym,readsym,endfile = range(0, len(tokenNames))
#===============================================================================
class symbol:
#===============================================================================
name = None # String representation
token = None; # Corresponding token
address = 0; # For variables, their runtime address
value = None # on defined for numbers
def __init__(self, name, token, value = 0):
self.name = name
self.token = token
self.address = 0 # for identifiers, their address
self.value = value # for numbers, their value
symtbl = {}; # The Symbol Table, a dictionary of symbols indexed by name
#======================================================================
# GLOBALS for output of Lexical Analyser
# Set by each call to GeToken()
token = None; # A symbol
line = "\n" # the complex source file as a string
charIndex = 0 # the position in the source
linenumber= 0 # The current number
EOF = chr(0)
#======================================================================
# Run Time Code Generation Variables
varptr = 500 # Arbitrary base address of memory for variables
codeptr = 10 # Address to output next instruction (for code)
#===============================================================================
# Symbol Table Management Routines
#===============================================================================
#===============================================================================
def addToSymTbl (name, token):
#===============================================================================
symtbl[name] = symbol(name, token) # Add a new symbol to the dictionary
return symtbl[name]
#===============================================================================
def lookup (thisName):
#===============================================================================
"# Find a given identifier in the Symbol Table, Return the symtbl entry"
if symtbl.has_key(thisName): # thisName has been seen before
return symtbl[thisName] # return the symtbl entry
else: return None
#===============================================================================
def initSymTbl():
#===============================================================================
"# Initialise Symbol Table, and preload reserved words"
addToSymTbl('var', varsym)
addToSymTbl('program', programsym)# VAR
addToSymTbl('while', whilesym) # WHILE
addToSymTbl('print', printsym) # PRINT
addToSymTbl('else', elsesym)
addToSymTbl('elif', elifsym)
addToSymTbl('if', ifsym)
addToSymTbl('declare', declaresym)
addToSymTbl('for', forsym)
addToSymTbl('None', nonesym)
addToSymTbl('continue', continuesym)
addToSymTbl('read', readsym)#READINT
addToSymTbl('do', dosym)
# Now add symbols - NB only single character symbols are here
# multicharacter one like ">=" are still to do
addToSymTbl( '=', assignsym)
addToSymTbl( '#', comment)
addToSymTbl( '<', lessthan)
addToSymTbl( '>', greaterthan)
addToSymTbl( '{', leftbrace )
addToSymTbl( '}', rightbrace)
addToSymTbl( '(', leftbracket)
addToSymTbl( ')', rightbracket)
addToSymTbl( '+', plus )
addToSymTbl( '-', minus)
addToSymTbl( ';', semicolon)
addToSymTbl( 'break', breaksym)
addToSymTbl( '*', mpy)
addToSymTbl( '/', div)
addToSymTbl( '[', leftsquarebrace)
addToSymTbl( ']', rightsquarebrace)
addToSymTbl( ':', colon)
addToSymTbl( ',', comma)
addToSymTbl( '.', dot)
addToSymTbl( '==', jumpeq)
addToSymTbl( '!=', jumpne)
addToSymTbl( '&&', andop)
addToSymTbl( '||', orop)
addToSymTbl( '"',quote)
addToSymTbl( EOF, endfile)
#===============================================================================
# Scanner Diagnostics
#===============================================================================
def printToken(tok):
#===============================================================================
" - display the specified token."
if tok.token == idsym:
print "Token = %10s, %-10s adr = %3d" %\
(tokenNames[tok.token], tok.name, tok.address)
elif tok.token == number:
print "Token = %10s %d" % (tokenNames[tok.token], tok.value)
else:
print "Token = %10s" % tokenNames[tok.token]
#==============================?=================================================
def dumpSymTbl():
#===============================================================================
""" Dump all the tokens in the symboltable """
print(" *** Symbol Table ***")
for name in symtbl.keys(): # keys is a list of the names (printable form of tokens)
tok = symtbl[name]
if tok.token == idsym:
printToken(tok)
#===============================================================================
def getch():
#===============================================================================
global line
global charIndex
global linenumber
while True:
if charIndex < len(line): # See if used up current line
ch = line[charIndex] # if not, get character
charIndex = charIndex+1 # & move pointer for next time
else:
# line = f.readline()
# if line == "": line = EOF
print "#End of File"
print "#--> ",
line = raw_input() +"\n" # read new line, adding \n so it's like f.readline()
# line = srcfile.read()
charIndex = 0 # & reset character pointer
linenumber = linenumber + 1
continue
if ch == "\n":
ch = " "
if ch == '?':
dumpSymTbl()
continue
return ch
#===============================================================================
def ungetch():
#===============================================================================
""" Unget the next character peeked at when building variables, numbers
and when distinguishing between >= and > ...
"""
global charIndex;
charIndex = charIndex-1;
#===============================================================================
def getoken():
#===============================================================================
""" GETOKEN - Put next token into the global TOKEN """
global token
x=0
ch = getch() # skip whitespace
while ch in ["\t", " ", "\n"]:
ch = getch()
# If ch is alphabetic then this is start of reserved word or an identifier
if ch.isalpha(): # Letter therefore it's either identifier or reserved word
name = ""
while ch.isalpha() or ch.isdigit() or ch == "_":
name = name + ch
ch = getch()
ungetch() # let terminator be used next time
token = lookup(name) # See if token's known
if token is None: # if not
token = addToSymTbl(name, idsym) # add as 'idsym'-IDENTIFIER
return # we've set token.token to either id or tokentype of reserved word
elif ch in ["{", "}", "(", ")", "[","]", "+", "-","*", "/", ";",",",":", EOF]:
token = lookup(ch) # preloaded with appropriate token
elif ch.isdigit():
# In the real version, build number and don't forget to end with ungetch()
while(ch.isdigit() == True):
x = str(x) + str(ch)
ch = getch()
ch = ungetch()
token = symbol(x, number, value = int(x)) # simplistic SINGLE DIGIT Ascii to Binary
return
# elif ch == "-":
# x = ""
# no =""
# ch = getch()
# if ch.isdigit() ==True:
# while ch.isdigit():
# x = str(x) + str(ch)
# ch = getch()
#
# ch = ungetch()
#
# no = "-" + str(x)
#
# token = symbol(no, number, value = int(no))
elif ch =='#':
str1 =""
ch = getch()
while(ch != " "):
str1 = str(str1) + str(ch)
ch = getch()
ch = getch()
token = symbol(str1, commentstr, value = str(str1)) # simplistic SINGLE DIGIT Ascii to Binary
print("#comment: " + str(str1))
return
elif ch =='"':
a =""
ch = getch()
while (ch != '"'):
a = str(a) + str(ch)
ch = getch()
ch = getch()
token = symbol(a, stringsym, value = str(a)) # simplistic SINGLE DIGIT Ascii to Binary
return
elif ch =="<":
ch = getch()
if ch == "=":
lt =""
lt ="<" + "="
token = symbol(lt, lessthanequal, value = str(lt)) # simplistic SINGLE DIGIT Ascii to Binary
return
else:
ch == ungetch()
token = symbol("<", lessthan, value = "<") # simplistic SINGLE DIGIT Ascii to Binary
return
elif ch =="!":
ne =""
if ch == "=":
ne ="!" + "="
ch = getch()
token = symbol(ne, jumpne, value = str(ne)) # simplistic SINGLE DIGIT Ascii to Binary
return
else:
ch == ungetch()
token = symbol("!", NOT , value = "!") # simplistic SINGLE DIGIT Ascii to Binary
return
elif ch =="=":
eq =""
if ch == "=":
eq ="=" + "="
ch = getch()
token = symbol(eq, jumpeq, value = str(eq)) # simplistic SINGLE DIGIT Ascii to Binary
return
else:
ch == ungetch()
token = symbol("=", assignsym, value = "=") # simplistic SINGLE DIGIT Ascii to Binary
return
elif ch ==">":
gt =""
ch = getch()
if ch == "=":
gt =">" + "="
ch = getch()
token = symbol(gt, lessthanequal, value = str(gt)) # simplistic SINGLE DIGIT Ascii to Binary
return
else:
ch == ungetch()
token = symbol(">", greaterthan, value = ">") # simplistic SINGLE DIGIT Ascii to Binary
return
else:
print "Unknown character -->%s<- decimal %d" % (ch,ord(ch))
sys.exit(1) # Abort Compilation
#======================================================================
# THE GRAMMAR
# <program> ::= { <id> ; <vars > <stmtlist> }
# <vars> ::= var { <id> ; } % DECLARATIONS
# <array> ::= [<expr>]
# <stmtlist> ::= <stmt> { ; <stmt> }
# <stmt> ::= print <id>
# <id> = <expr>
# <expr> ::= <factor> { (+ | - | * | /) <factor> } % No precedence
# <factor> ::= [+/-] ID | Number
#======================================================================
# Centralised Parser Error Message handler
#======================================================================
#===============================================================================
def error (msg):
#===============================================================================
print line
print "-" * charIndex,"^"
print("Error on %d - %s\n" % (number, msg))
printToken(token)
print("\n")
#===============================================================================
def emit (memadr, opcode, parameter):
#===============================================================================
"""EMIT CODE - Emit a of code with a Parameter
if first arg is zero - (the memory address), use and incr CODEPTR"""
global codeptr
if (memadr == 0):
memadr = codeptr
codeptr = codeptr+1
print "%6d %-8s %-7s" % (memadr, opcode, parameter)
#======================================================================
# VARIABLE DECLARATIONS
# <vars> ::= V { <id> ; }
#===============================================================================
def vars() :
#===============================================================================
ta = 0
tn = []
global varptr;
getoken();
if token.token == idsym:
ta = token.address
tn = token.name
getoken()
if token.token == leftsquarebrace:
getoken()
if token.token == number:
# emit(0, "loadv",token.value)
# emit(0, "store", token.value+300)
getoken()
if token.token == rightsquarebrace:
getoken()
else:
error("] expected")
else: error("number expected")
else:
if ta != 0:
print("%c already declared\n", tn);
# assignStmt()
else:
symtbl[tn].address = varptr;
varptr = varptr +1
# emit(0, "load", varptr)
if token.token == assignsym:
getoken()
expression()
if token.token == comma:
vars()
elif token.token == semicolon : getoken()
else: error("comma or semicolon expected in declaration")
#===============================================================================
def array():
#===============================================================================
global array;
getoken()
while (token.token == number):
print("#array address")
emit(0, "constant", token.value)
getoken();
if token.token == rightsquarebrace:getoken();
if token.token == assignsym:getoken();
while( token.token == number):
print("#store value")
emit(0, "load", 10)
emit(0, "add", 12)
emit(0, "store", 1)
emit(0, "loadv", token.value)
emit(0, "store-ind", 0)
getoken();
#======================================================================
# STMTLIST
# <stmtlist> ::= <stmt> { ; <stmt> }
#===============================================================================
def stmtList():
#===============================================================================
stmt()
while (token.token != rightbrace):
stmt()
#======================================================================
# STMT
#===============================================================================
def stmt():
#===============================================================================
""" <stmt> ::= print <expression|string>| read <vars> | <id> = <expression> |
if <condition> <stmt> [else <stmt>]| while <condition> <stmt>|
<stmtList> | do <stmsList> forever | break | continue
"""
global codeptr
thisStmtAdr = codeptr # Jump DEMO - not part of Stmt
# if token.token == arraysym:
# array()
if token.token == printsym:
printStmt()
elif token.token == readsym:
readStmt()
elif token.token == number:
expression()
elif token.token == idsym:
assignStmt()
elif token.token == ifsym:
ifStmt()
elif token.token == elsesym:
elseStmt()
elif token.token == whilesym:
whileStmt()
elif token.token == dosym:
doStmt()
elif token.token == breaksym:
breakStmt()
elif token.token == continuesym:
continueStmt()
elif token.token == leftbracket:
getoken()
elif token.token == leftbrace:
getoken()
# elif token.token == stringsym:
# print(str(token.name))
# getoken()
elif token.token == assignsym:
getoken()
elif token.token == commentstr:
# print(str(token.name))
getoken()
elif token.token == breaksym:
getoken()
elif token.token ==lessthanequal:
getoken()
elif token.token ==greaterthanequal:
getoken()
elif token.token == jumpeq:
getoken()
elif token.token == jumpne:
getoken()
elif token.token == rightbracket:
getoken()
elif token.token == semicolon:
getoken()
elif token.token == comma:
getoken()
elif token.token == rightbrace:
getoken()
else:
error("Expected start of a statement")
# emit (0, "return", thisStmtAdr) Jump DEMO need in break program
#===============================================================================
def printStmt():
#===============================================================================
""" <printStmt> ::= print <expression|string>"""
getoken()
# skip "print"
expression()
stmt()
emit(0, "writeint", 500)
# if token.token == rightbrace:
# print("\n*** Compilation finished ***\n")
#===============================================================================
def readStmt():
#===============================================================================
""" <readStmt> ::= read <vars>"""
getoken()
expression()
emit(0, "readint", 0)
emit(0, "store", 500)
#===============================================================================
def assignStmt():
#===============================================================================
"""
<id> = <expression>
"""
whichidentifier = token # Remember which ID on Left
getoken() # Get token after identifier
if token.token == assignsym:
getoken()
elif token.token == leftsquarebrace:
vars()
elif token.token == jumpeq:
getoken()
elif token.token == jumpne:
getoken()
elif token.token == rightbracket:
getoken()
elif token.token ==lessthanequal:
getoken()
elif token.token ==greaterthanequal:
getoken()
# elif token.token == idsym: factor()
else:
error("Expected = in assignment statement")
expression()
# Save result into LHS runtime address
def ifStmt():
#if-then-else
#===============================================================================
""" <ifStmt> ::= if <expression>"""
getoken() # skip "if"
expression()
stmt()
#===============================================================================
def elseStmt():
#if-then-else
#===============================================================================
""" <elseStmt> ::= else <expression>"""
getoken()
stmt()
expression()
emit(0, "return",0)
#===============================================================================
def whileStmt():
#===============================================================================
""" <whileStmt> ::= while (condition)statement"""
emit(0, "load", 201)
emit(0, "store", 501)
getoken()
expression() #num>0
stmt()
#===============================================================================
def expression():
#===============================================================================
"""
Leaves result in ACC at runtime
Use addresses 999 & 998 as Temporary variables
<expression> ::= <factor> { (+ | -) <factor> }
"""
if token.token == leftbracket: getoken()
factor()
while token.token == plus or token.token == minus or token.token == mpy or token.token == div or token.token == lessthan or token.token == greaterthan or token.token == lessthanequal or token.token == greaterthanequal or token.token == jumpne or token.token == jumpeq:
op = token # remember +/-
getoken()
# skip past +/-
#emit(0, "store", 997)
# Save current result
if token.token == leftbracket:
getoken()
factor()
if op.token == plus:
emit(0, "add", 211)
emit(0, "store", 500)
# if op.token == leftbracket:getoken()
elif op.token == minus: # Subtract - have to swap operand order
emit(0, "load", 500)
emit(0, "subtract", 201)
emit(0, "store", 500)
emit(0, "jump", 23)
elif op.token == mpy:
# emit(0, "load", 501)
emit(0, "mpy", 501)
emit(0, "store", 501)
elif op.token == div:
emit(0, "load", 999)
emit(0, "div", 998)
emit(0, "store", 8)
elif op.token == lessthan:
emit(0, "compare", 999)
emit(0, "jumplt", 80)
elif op.token == greaterthan:
emit(0, "load", 500)
emit(0, "compare", 200)
emit(0, "jumpgt", 50)
emit(50, "writeInt", 501)
elif op.token == lessthanequal:
emit(0, "compare", 201)
emit(0, "jumplt", 80)
emit(0, "store", 500)
elif op.token == greaterthanequal:
emit(0, "compare", 999)
emit(0, "jumpgt", 81)
emit(0, "jumpgt", 500)
elif op.token == jumpne:
emit(0, "compare", 999)
emit(0, "jumpne", 82)
emit(0, "loadv", 0)
emit(0, "store", 11)
elif op.token == jumpeq:
emit(0, "load", 500)
emit(0, "compare", 200)
emit(0, "jumpeq", 50)
emit(50, "writeInt", 501)
#===============================================================================
def factor():
#===============================================================================
"""
# FACTOR() - leaves result in ACC at runtime
<factor> ::= identifier | number
"""
if token.token == plus:
getoken()
#- (unary)
elif token.token == minus:
getoken()
if token.token == idsym:
emit(0, "load", token.address)
getoken()
elif token.token == stringsym:#################
print("#String: "+ str(token.name))
getoken()
elif token.token == number:
emit(0, "loadv", token.value)
emit(0, "store", 200+token.value)
getoken()
elif token.token == commentstr:
print ("#Comment: "+str(token.name))
getoken()
# elif token.token == assignsym:
# getoken()
elif token.token == leftbracket:
getoken()
# print "this is token",tokenNames[token.token]
elif token.token == leftsquarebrace: getoken()
elif token.token == rightbracket:
getoken()
elif token.token == breaksym:
getoken()
elif token.token == lessthanequal:
getoken()
elif token.token == greaterthanequal:
getoken()
elif token.token == jumpeq:
getoken()
elif token.token == rightsquarebrace:
getoken()
elif token.token == semicolon:
getoken()
elif token.token == leftbrace:
getoken()
elif token.token == rightbrace:
print("")
else:
error("Start Of Factor Expected")
#===============================================================================
def program():
#===============================================================================
if token.token == leftbrace:
getoken()
if token.token == programsym:
getoken()
# else: error("Program start with 'program' keyword")
if token.token == idsym:
getoken()
# else: error("Program name expected")
if token.token == semicolon:
getoken()
# else: error("Semicolon expected")
if token.token == declaresym :
vars()
if token.token == varsym :
vars()
if token.token == leftsquarebrace:
vars()
stmtList()
stmtList()
if token.token ==rightbrace:
print "#***Compilation Finished****"
#======================================================================
def main():
#======================================================================
global line
global srcfile
global charIndex
initSymTbl()
with open("tiny_1.txt") as srcfile:
# out1file = open('output.obj','w')
line = srcfile.read()
#out1file.write("hello")
# print line
charIndex = 0
debugScanner = False
if debugScanner: # Scanner Test Routine - Read a line and display the tokens
getoken()
while token.token is not None: # Skeleton for testing Scanner
printToken(token)
# y = str(token)
# out1file.write(y)
getoken()
sys.exit(1)
else:
getoken() # Parse Program according to the grammar
program()
#===============================================================================
# Main Compiler starts here
#===============================================================================
print "#Microcompiler.py v0.2"
emit(0, "load", 0)
main()
#emit(0, "constant", "'A'") #need in break,comment,exitloop,writer-if-read-write-ch program
#emit(0, "constant", 10)
#emit(0, "constant", 12)
#emit(0, "constant", 25)
#emit(0, "constant", -10)
"""
srcfile = open('tiny_1.txt', 'r')
lexer = shlex.shlex(srcfile)
for token in lexer:
print repr(token)
"""
#getoken()
#=======================================================================
# *** That's it folks - written by Giovanni Moretti - April 27, 2011 ***
#=======================================================================
| [
[
1,
0,
0.0011,
0.0011,
0,
0.66,
0,
540,
0,
1,
0,
0,
540,
0,
0
],
[
14,
0,
0.0033,
0.0011,
0,
0.66,
0.0233,
777,
1,
0,
0,
0,
0,
3,
0
],
[
8,
0,
0.0138,
0.0133,
0,
0... | [
"import re",
"__author__ = 'YeeHin Kwok'",
"\"\"\" Giovanni's MicroCompiler Demo\n\n<program> ::= { <id> ; <vars > <stmtlist> }\n<vars> ::= V { <id> ; } % DECLARATIONS\n\n<stmtlist> ::= <stmt> { ; <stmt> }\n<stmt> ::= P <id> | <id> = <expr>",... |
import re
__author__ = 'YeeHin Kwok'
""" Giovanni's MicroCompiler Demo
<program> ::= { <id> ; <vars > <stmtlist> }
<vars> ::= V { <id> ; } % DECLARATIONS
<stmtlist> ::= <stmt> { ; <stmt> }
<stmt> ::= P <id> | <id> = <expr>
<expr> ::= <factor> { (+ | -) <factor> } % No precedence
<factor> ::= ID | Number
"""
import sys
import shlex
#===============================================================================
# # Lexical Analyser - the "Scanner" - Define the TokenTypes
#===============================================================================
tokenNames = \
[ "unknownToken", "idsym", "assignsym", "leftbrace", "rightbrace",
"varsym", "semicolon", "whilesym", "leftbracket", "rightbracket",
"printsym", "ifsym", "equals", "lessthan", "greaterthan",
"number", "plus", "minus", "mpy", "div", "elsesym", "declaresym", "forsym", "andsym", "elifsym", "dosym", "returnsym","notsym",
"continuesym", "breaksym", "nonesym", "programsym", "functionsym", "leftsquarebrace", "rightsquarebrace",
"lessthanequal", "colon", "comma", "comment", "commentstr", "dot", " greaterthanequal", "jumpeq", "jumpne",
"andop", "orop", "quote ", "stringsym", "arraysym", "readsym", "endfile"]
# define the tokens as variables
unknownToken, idsym, assignsym, leftbrace, rightbrace, \
varsym, semicolon, whilesym, leftbracket, rightbracket, \
printsym, ifsym, equals, lessthan, greaterthan, \
number, plus, minus, mpy, div, elsesym, declaresym, forsym, andsym, elifsym, dosym, returnsym, notsym,\
continuesym, breaksym, nonesym, programsym, functionsym, leftsquarebrace, rightsquarebrace, \
lessthanequal, colon, comma, comment, commentstr, dot, greaterthanequal, jumpeq, jumpne, \
andop, orop, quote, stringsym, arraysym, readsym, endfile = range(0, len(tokenNames))
#===============================================================================
class symbol:
#===============================================================================
name = None # String representation
token = None; # Corresponding token
address = 0; # For variables, their runtime address
value = None # on defined for numbers
def __init__(self, name, token, value=0):
self.name = name
self.token = token
self.address = 0 # for identifiers, their address
self.value = value # for numbers, their value
symtbl = {}; # The Symbol Table, a dictionary of symbols indexed by name
#======================================================================
# GLOBALS for output of Lexical Analyser
# Set by each call to GeToken()
token = None; # A symbol
line = "\n" # the complex source file as a string
charIndex = 0 # the position in the source
linenumber = 0 # The current number
tokennum = 0
resultnum = 0
whichidentifier = None;
identifieraddress = 0;
i = 100
j = 100
counterafter = i
counterafter1 = j
EOF = chr(0)
#======================================================================
# Run Time Code Generation Variables
varptr = 500 # Arbitrary base address of memory for variables
codeptr = 10 # Address to output next instruction (for code)
#===============================================================================
# Symbol Table Management Routines
#===============================================================================
#===============================================================================
def addToSymTbl (name, token):
#===============================================================================
symtbl[name] = symbol(name, token) # Add a new symbol to the dictionary
return symtbl[name]
#===============================================================================
def lookup (thisName):
#===============================================================================
"# Find a given identifier in the Symbol Table, Return the symtbl entry"
if symtbl.has_key(thisName): # thisName has been seen before
return symtbl[thisName] # return the symtbl entry
else: return None
#===============================================================================
def initSymTbl():
#===============================================================================
"# Initialise Symbol Table, and preload reserved words"
addToSymTbl('var', varsym) # VAR
addToSymTbl('program', programsym)
addToSymTbl('function', functionsym)
addToSymTbl('while', whilesym) # WHILE
addToSymTbl('print', printsym) # PRINT
addToSymTbl('else', elsesym)
addToSymTbl('elif', elifsym)
addToSymTbl('if', ifsym)
addToSymTbl('declare', declaresym)
addToSymTbl('for', forsym)
addToSymTbl('None', nonesym)
addToSymTbl('continue', continuesym)
addToSymTbl('read', readsym) # READINT
addToSymTbl('do', dosym)
addToSymTbl('return', returnsym)
addToSymTbl('not', notsym)
# Now add symbols - NB only single character symbols are here
# multicharacter one like ">=" are still to do
addToSymTbl('=', assignsym)
addToSymTbl('#', comment)
addToSymTbl('<', lessthan)
addToSymTbl('>', greaterthan)
addToSymTbl('{', leftbrace)
addToSymTbl('}', rightbrace)
addToSymTbl('(', leftbracket)
addToSymTbl(')', rightbracket)
addToSymTbl('+', plus)
addToSymTbl('-', minus)
addToSymTbl(';', semicolon)
addToSymTbl('break', breaksym)
addToSymTbl('*', mpy)
addToSymTbl('/', div)
addToSymTbl('[', leftsquarebrace)
addToSymTbl(']', rightsquarebrace)
addToSymTbl(':', colon)
addToSymTbl(',', comma)
addToSymTbl('.', dot)
addToSymTbl('==', jumpeq)
addToSymTbl('!=', jumpne)
addToSymTbl('&&', andop)
addToSymTbl('||', orop)
addToSymTbl('"', quote)
addToSymTbl(EOF, endfile)
#===============================================================================
# Scanner Diagnostics
#===============================================================================
def printToken(tok):
#===============================================================================
" - display the specified token."
if tok.token == idsym:
print "Token = %10s, %-10s adr = %3d, val = %d" % \
(tokenNames[tok.token], tok.name, tok.address, tok.value)
elif tok.token == number:
print "Token = %10s %d" % (tokenNames[tok.token], tok.value)
else:
print "Token = %10s" % tokenNames[tok.token]
#==============================?=================================================
def dumpSymTbl():
#===============================================================================
""" Dump all the tokens in the symboltable """
print("# *** Symbol Table ***")
for name in symtbl.keys(): # keys is a list of the names (printable form of tokens)
tok = symtbl[name]
if tok.token == idsym:
print("#"),
printToken(tok)
#===============================================================================
def getch():
#===============================================================================
global line
global charIndex
global linenumber
while True:
if charIndex < len(line): # See if used up current line
ch = line[charIndex] # if not, get character
charIndex = charIndex + 1 # & move pointer for next time
else:
# line = f.readline()
# if line == "": line = EOF
dumpSymTbl()
print "#End of File"
print "#--> ",
line = raw_input() + "\n" # read new line, adding \n so it's like f.readline()
# line = srcfile.read()
charIndex = 0 # & reset character pointer
linenumber = linenumber + 1
continue
if ch == "\n":
ch = " "
if ch == '?':
dumpSymTbl()
continue
return ch
#===============================================================================
def ungetch():
#===============================================================================
""" Unget the next character peeked at when building variables, numbers
and when distinguishing between >= and > ...
"""
global charIndex;
charIndex = charIndex - 1;
#===============================================================================
def getoken():
#===============================================================================
""" GETOKEN - Put next token into the global TOKEN """
global token
global i
global m
global counterafter
global counterafter1
x = 0
ch = getch() # skip whitespace
while ch in ["\t", " ", "\n"]:
ch = getch()
# If ch is alphabetic then this is start of reserved word or an identifier
if ch.isalpha(): # Letter therefore it's either identifier or reserved word
name = ""
while ch.isalpha() or ch.isdigit() or ch == "_":
name = name + ch
ch = getch()
ungetch() # let terminator be used next time
token = lookup(name) # See if token's known
if token is None: # if not
token = addToSymTbl(name, idsym) # add as 'idsym'-IDENTIFIER
return # we've set token.token to either id or tokentype of reserved word
elif ch in ["{", "}", "(", ")", "[", "]", "+", "-", "*", "/", ";", ",", ":", EOF]:
token = lookup(ch) # preloaded with appropriate token
elif ch.isdigit():
# In the real version, build number and don't forget to end with ungetch()
while(ch.isdigit() == True):
x = str(x) + str(ch)
ch = getch()
ch = ungetch()
token = symbol(x, number, value=int(x)) # simplistic SINGLE DIGIT Ascii to Binary
return
# elif ch == "-":
# x = ""
# no =""
# ch = getch()
# if ch.isdigit() ==True:
# while ch.isdigit():
# x = str(x) + str(ch)
# ch = getch()
#
# ch = ungetch()
#
# no = "-" + str(x)
#
# token = symbol(no, number, value = int(no))
elif ch == '#':
str1 = ""
ch = getch()
while(ch != " "):
str1 = str(str1) + str(ch)
ch = getch()
ch = getch()
token = symbol(str1, commentstr, value=str(str1)) # simplistic SINGLE DIGIT Ascii to Binary
print("#comment: " + str(str1))
return
elif ch == '"':
a = ""
ch = getch()
counterafter1 =counterafter
i=counterafter
if counterafter != 100:
counterafter=counterafter+4;
counterafter = i
while (ch != '"'):
a = str(a) + str(ch)
if ch != " ":
b = "'"+ch+"'"
emit(i, "constant",b)
ch = getch()
i=i+1
emit(i, "constant", 13)
emit(i+1, "constant", 0)
# emit(i+2, "writech", '')
emit(i+2, "return", '')
ch = getch()
counterafter=i+3
token = symbol(a, stringsym, value=str(a)) # simplistic SINGLE DIGIT Ascii to Binary
# printMsg()
return
elif ch == "<":
ch = getch()
if ch == "=":
lt = ""
lt = "<" + "="
token = symbol(lt, lessthanequal, value=str(lt)) # simplistic SINGLE DIGIT Ascii to Binary
return
else:
ch == ungetch()
token = symbol("<", lessthan, value="<") # simplistic SINGLE DIGIT Ascii to Binary
return
elif ch == "!":
ne = ""
ch = getch()
if ch == "=":
ne = "!" + "="
token = symbol(ne, jumpne, value=str(ne)) # simplistic SINGLE DIGIT Ascii to Binary
return
else:
ch == ungetch()
token = symbol("!", NOT , value="!") # simplistic SINGLE DIGIT Ascii to Binary
return
elif ch == "=":
eq = ""
ch = getch()
if ch == "=":
eq = "=" + "="
token = symbol(eq, jumpeq, value=str(eq)) # simplistic SINGLE DIGIT Ascii to Binary
return
else:
ch == ungetch()
token = symbol("=", assignsym, value="=") # simplistic SINGLE DIGIT Ascii to Binary
return
elif ch == ">":
gt = ""
ch = getch()
if ch == "=":
gt = ">" + "="
token = symbol(gt, greaterthanequal, value=str(gt)) # simplistic SINGLE DIGIT Ascii to Binary
return
else:
ch == ungetch()
token = symbol(">", greaterthan, value=">") # simplistic SINGLE DIGIT Ascii to Binary
return
else:
print "Unknown character -->%s<- decimal %d" % (ch, ord(ch))
sys.exit(1) # Abort Compilation
#======================================================================
# THE GRAMMAR
# <program> ::= { <id> ; <vars > <stmtlist> }
# <vars> ::= var { <id> ; } % DECLARATIONS
# <array> ::= [<expr>]
# <stmtlist> ::= <stmt> { ; <stmt> }
# <stmt> ::= print <id>
# <id> = <expr>
# <expr> ::= <term> { (+ | - ) <term> }
# <term> ::= <factor> { (*|/) factor}
# <factor> ::= [+/-] ID | Number | expression
#======================================================================
# Centralised Parser Error Message handler
#======================================================================
#===============================================================================
def error (msg):
#===============================================================================
print line
print "-" * charIndex, "^"
print("Error on %d - %s\n" % (number, msg))
printToken(token)
print("\n")
#===============================================================================
def emit (memadr, opcode, parameter):
#===============================================================================
"""EMIT CODE - Emit a of code with a Parameter
if first arg is zero - (the memory address), use and incr CODEPTR"""
global codeptr
if (memadr == 0):
memadr = codeptr
codeptr = codeptr + 1
print "%6d %-8s %-7s" % (memadr, opcode, parameter)
#======================================================================
# VARIABLE DECLARATIONS
# <vars> ::= V { <id> ; }
# <vars> ::= <id>[array]
#===============================================================================
def vars() :
#===============================================================================
ta = 0
tn = []
global varptr;
global arraynum;
getoken();
if token.token == idsym:
ta = token.address
tn = token.name
getoken()
if token.token == leftsquarebrace:
getoken()
if token.token == number: #number
print("#The address for "+ str(tn)+ " are ")
symtbl[tn].address = varptr;
emit(0, "constant", varptr)
while (token.value != 0):
# print("#address at " + str(varptr))
emit(0, "constant", token.value)
varptr = varptr + 1
token.value= token.value-1
array()
elif token.token == idsym: #id
# getoken()
expression()
getoken()
if token.token == rightsquarebrace:
getoken()
else:
if ta != 0:
print("%c already declared\n", tn);
#assignStmt()
else:
symtbl[tn].address = varptr;
varptr = varptr + 1
# emit(0, "load", varptr)
if token.token == assignsym:
getoken()
expression()
if token.token == rightsquarebrace:
getoken()
if token.token == rightbracket:
getoken()
if token.token == comma:
vars()
if token.token == number:
arraynum = token.value;
print("#arraynum "+str(arraynum))
# if arraynum =
emit(0, "loadv", token.value)
emit(0, "add", 11)
emit(0, "store", 1)
getoken()
if token.token == rightsquarebrace:
getoken()
if token.token == assignsym:
getoken()
if token.token == number:
emit(0, "loadv", token.value)
emit(0, "store-ind", 0)
if token.token == plus or token.token == minus or token.token == mpy or token.token == div:
if token.token == plus:
emit(0, "load", 1)
emit(0, "load-ind", 0)
emit(0, "store", 1)
getoken()
if token.token == number:
emit(0, "loadv", token.value)
emit(0, "add", 1)
emit(0, "store", 507)
getoken()
# if token.token == plus or token.token == minus or token.token == mpy or token.token == div:
# getoken()
elif token.token == leftbrace:
getoken()
elif token.token == semicolon : getoken()
else: error("comma or semicolon expected in declaration")
#===============================================================================
def array():
# [expression]
#===============================================================================
global array;
expression()
print("#End of array expression")
"""
emit(0, "jump", 60)
emit(60, "load", 11)
emit(61, "add", 12)
emit(62, "store", 1)
"""
#======================================================================
# STMTLIST
# <stmtlist> ::= <stmt> { ; <stmt> }
#===============================================================================
def stmtList():
#===============================================================================
stmt()
while (token.token != rightbrace):
stmt()
#======================================================================
# STMT
#===============================================================================
def stmt():
#===============================================================================
""" <stmt> ::= print <expression|string>| read <vars> | <id> = <expression> |
if <condition> <stmt> [else <stmt>]| while <condition> <stmt>|
<stmtList> | do <stmsList> forever | break | continue
"""
global codeptr
thisStmtAdr = codeptr # Jump DEMO - not part of Stmt
# if token.token == arraysym:
# array()
if token.token == vars:
expression()
elif token.token == ifsym:
ifStmt()
if token.token == elsesym:
elseStmt()
elif token.token == whilesym:
whileStmt()
elif token.token == stmtList:
stmtList()
elif token.token == printsym:
printStmt()
elif token.token == readsym:
readStmt()
elif token.token == dosym:
doStmt()
foreverStmt()
elif token.token == breaksym:
breakStmt()
elif token.token == continuesym:
continueStmt()
elif token.token == number:
expression()
elif token.token == idsym:
assignStmt()
elif token.token == functionsym:
function()
elif token.token == returnsym:
returnStmt()
elif token.token == stringsym:
# print(str(token.name))
printMsg()
getoken()
elif token.token == leftbracket or token.token == rightbracket or token.token == leftbrace or token.token == rightbrace or token.token == rightsquarebrace or token.token == assignsym:
getoken()
elif token.token == commentstr or token.token == breaksym:
# print(str(token.name))
getoken()
elif token.token == lessthan or token.token == greaterthan or token.token == lessthanequal or token.token == greaterthanequal or token.token == jumpeq or token.token == jumpne:
relational_op()
elif token.token == plus or token.token == minus or token.token == mpy or token.token == div:
expression
elif token.token == semicolon or token.token == comma:
getoken()
else:
error("Expected start of a statement")
# emit (0, "return", thisStmtAdr) Jump DEMO need in break program
#===============================================================================
def printStmt():
#===============================================================================
""" <printStmt> ::= print <expression|string>"""
global idaddress
getoken()# skip "print"
getoken()
if token.token == stringsym:
printMsg()
# emit(0, "writeint", 501)
if token.token == idsym:
emit(0, "writeint", 501)
else:
emit(0, "writeint", 501)
# emit(0, "writeint", 7)
#===============================================================================
def printMsg():
#===============================================================================
""" <printMsg> ::= printMsg <expression>"""
# print("#"+str(counterafter)+ " counterafter")
# print("#"+str(counterafter1)+ " counterafter1")
# if counterafter != 100:
# emit(0,"loadv",counterafter )
emit(0, "loadv", counterafter1)
emit(0, "store", 1)
emit(0, "call", 400)
emit(400, "load-Ind", 0)
emit(401, "jumpeq", 405)
emit(402, "writech",0)
emit(403, "increment", 1)
emit(404, "jump", 400)
emit(405, "return", '')
getoken()
#===============================================================================
def readStmt():
#===============================================================================
""" <readStmt> ::= read <vars>"""
getoken()
emit(0, "readint", 7)
emit(0, "load", 7)
emit(0, "store", 500)
getoken()
#===============================================================================
def assignStmt():
#===============================================================================
"""
<id> = <expression>
"""
global tokennum
global resultnum
global whichidentifier
whichidentifier = token.name # Remember which ID on Left
whichidaddress = token.address
print("#whichidentifier: " +str(whichidentifier))
getoken() # Get token after identifier
if token.token == assignsym:
getoken()
elif token.token == leftsquarebrace:
vars()
elif token.token == leftbrace:
getoken()
elif token.token == jumpeq:
getoken()
elif token.token == jumpne:
getoken()
elif token.token == rightbracket:
getoken()
elif token.token == lessthanequal:
getoken()
elif token.token == idsym:
getoken()
elif token.token == leftbracket:
getoken()
elif token.token == comma:
getoken()
elif token.token == greaterthanequal:
getoken()
# elif token.token == idsym: factor()
else:
error("Expected = in assignment statement")
# print("#Store value")
expression()
passtoken = token.value
# print(str(tokennum))
symtbl[whichidentifier].value = tokennum
# emit(0, "store", whichidaddress)
getoken()
# emit(0, "writeint", whichidaddress)
# print("#assign " + str(whichidentifier))
# print("#assign " + str(whichidaddress))
# Save result into LHS runtime address
# expression()
#===============================================================================
def ifStmt():
# if-then-else
#===============================================================================
""" <ifStmt> ::= if <expression>"""
print("#IFSmt")
getoken() # skip "if"
condition()
stmt()
#===============================================================================
def elseStmt():
# if-then-else
#===============================================================================
""" <elseStmt> ::= else <expression>"""
print("#ElseSmt")
# emit(200, "jump", 47) # less than 2 go to else
getoken()
stmt()
# emit(314, "jump", 22)
#===============================================================================
def whileStmt():
#===============================================================================
""" <whileStmt> ::= while (condition)statement"""
# emit(0, "load", 201)
emit(0, "store", 502)
getoken()
expression() # num>0
stmtList()
emit(0, "jump", 25)
#===============================================================================
def returnStmt():
#===============================================================================
emit(600,"add", 201)
emit(601,"store", 502)
emit(602,"return", '')
getoken()
#===============================================================================
def condition():
#===============================================================================
if token.token == notsym:
emit(0, "Not",'')
getoken()
conditionalexp()
#===============================================================================
def conditionalexp():
#===============================================================================
expression()
relational_op()
expression()
#===============================================================================
def relational_op():
#===============================================================================
if token.token == lessthan or token.token == greaterthan or token.token == lessthanequal or token.token == greaterthanequal or token.token == jumpne or token.token == jumpeq:
op = token # remember -
getoken() # skip past -
term()
if op.token == lessthan:
# emit(0, "load", 501)
emit(0, "compare", 500)
emit(0, "jumplt", 43)
elif op.token == greaterthan:
# emit(0, "load", 200)
emit(0, "compare", 500)
emit(0, "jumpgt", 43)
elif op.token == lessthanequal:
# emit(0, "load", 200)
emit(0, "compare", 500)
emit(0, "jumplt", 43)
emit(0, "jumpeq", 43)
# emit(300, "writeInt", 502)
elif op.token == greaterthanequal:
# emit(0, "load", 200)
emit(0, "compare", 500)
emit(0, "jumpgt", 43)
emit(0, "jumpeq", 43)
# emit(300, "writeInt", 502)
elif op.token == jumpne:
emit(0, "load", 205)
emit(0, "compare", 502)
emit(0, "jumpne", 310)
emit(0, "writeInt", 0)
emit(0, "halt", 0)
# emit(310, "writeInt", 502)
elif op.token == jumpeq:
emit(0, "load", 200)
emit(0, "compare", 502)
emit(0, "jumpeq", 29)
#===============================================================================
def expression():
#===============================================================================
"""
Leaves result in ACC at runtime
Use addresses 999 & 998 as Temporary variables
<expression> ::= <factor> { (+ | -) <factor> } <- wrong
<expression> ::= <term> { (+ | -) <term> }
"""
global whichidentifier
global idaddress
global idvalue
if whichidentifier == None:
getoken()
else:
idaddress = symtbl[whichidentifier].address
# print("#Identifier address " + str(idaddress))
"""
idvalue = symtbl[whichidentifier].value
print("#Identifier value " + str(idvalue))
"""
if token.token == leftbracket:
getoken()
term()
while token.token == plus or token.token == minus:
op = token # remember -
getoken() # skip past -
term()
if op.token == plus:
emit(0, "add", 501)
# emit(0, "store", 500)
# emit(0, "writeInt", 500)
elif op.token == minus: # Subtract - have to swap operand order
emit(0, "load", 501)
emit(0, "subtract", 1)
emit(0, "store", 501)
getoken()
term()
# print("term 1" + str(factor()))
## 1st start==============================================================================
while token.token == plus or token.token == minus:
op = token # remember -
getoken() # skip past -
# emit(0, "store", 997) # Save current result
term()
# print("term 2" + str(term))
# print("#whichidentifier " + whichidentifier)
if op.token == plus:
emit(0, "add", 502)
# emit(0, "store", 500)
# emit(0, "writeInt", 500)
elif op.token == minus: # Subtract - have to swap operand order
emit(0, "load", 500)
emit(0, "subtract", 1)
emit(0, "store", idaddress)
# emit(0, "writeInt", 501)
#===============================================================================
def term():
#===============================================================================
"""
term::= factor {(*|/) factor}
"""
global idaddress
factor()
while token.token == mpy or token.token == div:
op = token # remember -
getoken() # skip past -
factor()
if op.token == mpy:
emit(0, "mpy", 502)
# emit(0, "store", 205)
emit(0, "store", 502)
# emit(0, "store", 210)
while token.token == mpy:
op2 = token # remember -
getoken() # skip past -
factor()
emit(0, "mpy", 502)
# emit(0, "store", 205)
emit(0, "store", idaddress)
elif op.token == div:
emit(0, "load", 502)
emit(0, "div", 202)
emit(0, "store", 503)
#===============================================================================
def factor():
#===============================================================================
"""
# FACTOR() - leaves result in ACC at runtime
<factor> ::= [+|-] identifier | number | (expression)
"""
global tokennum
global whichidentifier
global idaddress
global idvalue
# [+|-] number
if token.token == plus:
getoken()
if token.token == number:
emit(0, "loadv", token.value)
emit(0, "store", 200 + token.value)
getoken()
# - (unary)
elif token.token == minus:
getoken()
if token.token == number:
emit(0, "loadv", 0-token.value)
emit(0, "store", 200 + token.value)
getoken()
elif token.token == number:
emit(0, "loadv", token.value)
emit(0, "store", 1)
tokennum = token.value
getoken()
# identifier
elif token.token == idsym:
# print("#token address " + str(token.address))
# print("#token value " + str(token.value))
emit(0, "load", token.address)
getoken()
# (expression)
elif token.token == leftbracket:
expression()
elif token.token == lessthan or token.token == greaterthan or token.token == lessthanequal or token.token == greaterthanequal or token.token == jumpeq or token.token == jumpne:
relational_op()
elif token.token == stringsym: #################
print("#String: " + str(token.name))
# printMsg()
printStmt()
getoken()
elif token.token == commentstr or token.token == rightbracket or token.token == leftsquarebrace or token.token == rightsquarebrace:
# print ("#Comment: " + str(token.name))
getoken()
elif token.token == breaksym:
emit(0,"halt", 0)
elif token.token == semicolon or token.token == comma:
getoken()
elif token.token == leftbrace:
getoken()
elif token.token == rightbrace:
print("")
elif token.token == ifsym:
ifStmt()
elif token.token == printsym or token.token == returnsym or token.token == functionsym:
getoken()
else:
error("Start Of Factor Expected")
"""
elif token.token == assignsym:
getoken()
elif token.token == lessthanequal:
getoken()
elif token.token == greaterthanequal:
getoken()
elif token.token == jumpeq:
getoken()
"""
#===============================================================================
def function():
#===============================================================================
if token.token == functionsym:
getoken()
if token.token == idsym:
getoken()
if token.token == idsym:
getoken()
if token.token == varsym :
vars()
if token.token == declaresym :
vars()
if token.token == varsym :
vars()
if token.token == leftbrace:
getoken()
stmtList()
if token.token == rightbrace:
print ("#---Function Finished---")
#===============================================================================
def program():
#===============================================================================
if token.token == programsym:
getoken()
else: error("Program start with 'program' keyword")
if token.token == idsym:
getoken()
if token.token == semicolon:
getoken()
# else: error("Semicolon expected")
if token.token == declaresym :
vars()
if token.token == varsym :
vars()
if token.token == semicolon:
getoken()
if token.token == functionsym:
function()
if token.token == semicolon:
getoken()
if token.token == leftbrace:
getoken()
stmtList()
stmtList()
if token.token == rightbrace:
print "#***Compilation Finished****"
#======================================================================
def main():
#======================================================================
global line
global srcfile
global charIndex
initSymTbl()
with open("test.txt") as srcfile:
# out1file = open('output.obj','w')
line = srcfile.read()
# out1file.write("hello")
# print line
charIndex = 0
debugScanner = False
if debugScanner: # Scanner Test Routine - Read a line and display the tokens
getoken()
while token.token is not None: # Skeleton for testing Scanner
printToken(token)
# y = str(token)
# out1file.write(y)
getoken()
sys.exit(1)
else:
getoken() # Parse Program according to the grammar
program()
#===============================================================================
# Main Compiler starts here
#===============================================================================
print "#Microcompiler.py v0.2"
emit(0, "load", 9)
main()
# emit(0, "constant", "'A'") #need in break,comment,exitloop,writer-if-read-write-ch program
# emit(0, "constant", 10)
# emit(0, "constant", 12)
# emit(0, "constant", 25)
# emit(0, "constant", -10)
"""
srcfile = open('tiny_1.txt', 'r')
lexer = shlex.shlex(srcfile)
for token in lexer:
print repr(token)
"""
# getoken()
#=======================================================================
# *** That's it folks - written by Giovanni Moretti - April 27, 2011 ***
#=======================================================================
| [
[
1,
0,
0.0008,
0.0008,
0,
0.66,
0,
540,
0,
1,
0,
0,
540,
0,
0
],
[
14,
0,
0.0024,
0.0008,
0,
0.66,
0.0172,
777,
1,
0,
0,
0,
0,
3,
0
],
[
8,
0,
0.0101,
0.0097,
0,
0... | [
"import re",
"__author__ = 'YeeHin Kwok'",
"\"\"\" Giovanni's MicroCompiler Demo\n\n<program> ::= { <id> ; <vars > <stmtlist> }\n<vars> ::= V { <id> ; } % DECLARATIONS\n\n<stmtlist> ::= <stmt> { ; <stmt> }\n<stmt> ::= P <id> | <id> = <expr>",... |
import re
__author__ = 'YeeHin Kwok'
""" Giovanni's MicroCompiler Demo
<program> ::= { <id> ; <vars > <stmtlist> }
<vars> ::= V { <id> ; } % DECLARATIONS
<stmtlist> ::= <stmt> { ; <stmt> }
<stmt> ::= P <id> | <id> = <expr>
<expr> ::= <factor> { (+ | -) <factor> } % No precedence
<factor> ::= ID | Number
"""
import sys
import shlex
#===============================================================================
# # Lexical Analyser - the "Scanner" - Define the TokenTypes
#===============================================================================
tokenNames = \
[ "unknownToken", "idsym", "assignsym", "leftbrace", "rightbrace",
"varsym", "semicolon", "whilesym", "leftbracket", "rightbracket",
"printsym", "ifsym", "equals", "lessthan", "greaterthan",
"number", "plus", "minus", "mpy", "div", "elsesym", "declaresym", "forsym", "andsym", "elifsym", "dosym", "returnsym","notsym",
"continuesym", "breaksym", "nonesym", "programsym", "functionsym", "leftsquarebrace", "rightsquarebrace",
"lessthanequal", "colon", "comma", "comment", "commentstr", "dot", " greaterthanequal", "jumpeq", "jumpne",
"andop", "orop", "quote ", "stringsym", "arraysym", "readsym", "endfile"]
# define the tokens as variables
unknownToken, idsym, assignsym, leftbrace, rightbrace, \
varsym, semicolon, whilesym, leftbracket, rightbracket, \
printsym, ifsym, equals, lessthan, greaterthan, \
number, plus, minus, mpy, div, elsesym, declaresym, forsym, andsym, elifsym, dosym, returnsym, notsym,\
continuesym, breaksym, nonesym, programsym, functionsym, leftsquarebrace, rightsquarebrace, \
lessthanequal, colon, comma, comment, commentstr, dot, greaterthanequal, jumpeq, jumpne, \
andop, orop, quote, stringsym, arraysym, readsym, endfile = range(0, len(tokenNames))
#===============================================================================
class symbol:
#===============================================================================
name = None # String representation
token = None; # Corresponding token
address = 0; # For variables, their runtime address
value = None # on defined for numbers
def __init__(self, name, token, value=0):
self.name = name
self.token = token
self.address = 0 # for identifiers, their address
self.value = value # for numbers, their value
symtbl = {}; # The Symbol Table, a dictionary of symbols indexed by name
#======================================================================
# GLOBALS for output of Lexical Analyser
# Set by each call to GeToken()
token = None; # A symbol
line = "\n" # the complex source file as a string
charIndex = 0 # the position in the source
linenumber = 0 # The current number
tokennum = 0
resultnum = 0
whichidentifier = None;
identifieraddress = 0;
i = 100
j = 100
counterafter = i
counterafter1 = j
EOF = chr(0)
#======================================================================
# Run Time Code Generation Variables
varptr = 500 # Arbitrary base address of memory for variables
codeptr = 10 # Address to output next instruction (for code)
#===============================================================================
# Symbol Table Management Routines
#===============================================================================
#===============================================================================
def addToSymTbl (name, token):
#===============================================================================
symtbl[name] = symbol(name, token) # Add a new symbol to the dictionary
return symtbl[name]
#===============================================================================
def lookup (thisName):
#===============================================================================
"# Find a given identifier in the Symbol Table, Return the symtbl entry"
if symtbl.has_key(thisName): # thisName has been seen before
return symtbl[thisName] # return the symtbl entry
else: return None
#===============================================================================
def initSymTbl():
#===============================================================================
"# Initialise Symbol Table, and preload reserved words"
addToSymTbl('var', varsym) # VAR
addToSymTbl('program', programsym)
addToSymTbl('function', functionsym)
addToSymTbl('while', whilesym) # WHILE
addToSymTbl('print', printsym) # PRINT
addToSymTbl('else', elsesym)
addToSymTbl('elif', elifsym)
addToSymTbl('if', ifsym)
addToSymTbl('declare', declaresym)
addToSymTbl('for', forsym)
addToSymTbl('None', nonesym)
addToSymTbl('continue', continuesym)
addToSymTbl('read', readsym) # READINT
addToSymTbl('do', dosym)
addToSymTbl('return', returnsym)
addToSymTbl('not', notsym)
# Now add symbols - NB only single character symbols are here
# multicharacter one like ">=" are still to do
addToSymTbl('=', assignsym)
addToSymTbl('#', comment)
addToSymTbl('<', lessthan)
addToSymTbl('>', greaterthan)
addToSymTbl('{', leftbrace)
addToSymTbl('}', rightbrace)
addToSymTbl('(', leftbracket)
addToSymTbl(')', rightbracket)
addToSymTbl('+', plus)
addToSymTbl('-', minus)
addToSymTbl(';', semicolon)
addToSymTbl('break', breaksym)
addToSymTbl('*', mpy)
addToSymTbl('/', div)
addToSymTbl('[', leftsquarebrace)
addToSymTbl(']', rightsquarebrace)
addToSymTbl(':', colon)
addToSymTbl(',', comma)
addToSymTbl('.', dot)
addToSymTbl('==', jumpeq)
addToSymTbl('!=', jumpne)
addToSymTbl('&&', andop)
addToSymTbl('||', orop)
addToSymTbl('"', quote)
addToSymTbl(EOF, endfile)
#===============================================================================
# Scanner Diagnostics
#===============================================================================
def printToken(tok):
#===============================================================================
" - display the specified token."
if tok.token == idsym:
print "Token = %10s, %-10s adr = %3d, val = %d" % \
(tokenNames[tok.token], tok.name, tok.address, tok.value)
elif tok.token == number:
print "Token = %10s %d" % (tokenNames[tok.token], tok.value)
else:
print "Token = %10s" % tokenNames[tok.token]
#==============================?=================================================
def dumpSymTbl():
#===============================================================================
""" Dump all the tokens in the symboltable """
print("# *** Symbol Table ***")
for name in symtbl.keys(): # keys is a list of the names (printable form of tokens)
tok = symtbl[name]
if tok.token == idsym:
print("#"),
printToken(tok)
#===============================================================================
def getch():
#===============================================================================
global line
global charIndex
global linenumber
while True:
if charIndex < len(line): # See if used up current line
ch = line[charIndex] # if not, get character
charIndex = charIndex + 1 # & move pointer for next time
else:
# line = f.readline()
# if line == "": line = EOF
dumpSymTbl()
print "#End of File"
print "#--> ",
line = raw_input() + "\n" # read new line, adding \n so it's like f.readline()
# line = srcfile.read()
charIndex = 0 # & reset character pointer
linenumber = linenumber + 1
continue
if ch == "\n":
ch = " "
if ch == '?':
dumpSymTbl()
continue
return ch
#===============================================================================
def ungetch():
#===============================================================================
""" Unget the next character peeked at when building variables, numbers
and when distinguishing between >= and > ...
"""
global charIndex;
charIndex = charIndex - 1;
#===============================================================================
def getoken():
#===============================================================================
""" GETOKEN - Put next token into the global TOKEN """
global token
global i
global m
global counterafter
global counterafter1
x = 0
ch = getch() # skip whitespace
while ch in ["\t", " ", "\n"]:
ch = getch()
# If ch is alphabetic then this is start of reserved word or an identifier
if ch.isalpha(): # Letter therefore it's either identifier or reserved word
name = ""
while ch.isalpha() or ch.isdigit() or ch == "_":
name = name + ch
ch = getch()
ungetch() # let terminator be used next time
token = lookup(name) # See if token's known
if token is None: # if not
token = addToSymTbl(name, idsym) # add as 'idsym'-IDENTIFIER
return # we've set token.token to either id or tokentype of reserved word
elif ch in ["{", "}", "(", ")", "[", "]", "+", "-", "*", "/", ";", ",", ":", EOF]:
token = lookup(ch) # preloaded with appropriate token
elif ch.isdigit():
# In the real version, build number and don't forget to end with ungetch()
while(ch.isdigit() == True):
x = str(x) + str(ch)
ch = getch()
ch = ungetch()
token = symbol(x, number, value=int(x)) # simplistic SINGLE DIGIT Ascii to Binary
return
# elif ch == "-":
# x = ""
# no =""
# ch = getch()
# if ch.isdigit() ==True:
# while ch.isdigit():
# x = str(x) + str(ch)
# ch = getch()
#
# ch = ungetch()
#
# no = "-" + str(x)
#
# token = symbol(no, number, value = int(no))
elif ch == '#':
str1 = ""
ch = getch()
while(ch != " "):
str1 = str(str1) + str(ch)
ch = getch()
ch = getch()
token = symbol(str1, commentstr, value=str(str1)) # simplistic SINGLE DIGIT Ascii to Binary
print("#comment: " + str(str1))
return
elif ch == '"':
a = ""
ch = getch()
counterafter1 =counterafter
i=counterafter
if counterafter != 100:
counterafter=counterafter+4;
counterafter = i
while (ch != '"'):
a = str(a) + str(ch)
if ch != " ":
b = "'"+ch+"'"
emit(i, "constant",b)
ch = getch()
i=i+1
emit(i, "constant", 13)
emit(i+1, "constant", 0)
# emit(i+2, "writech", '')
emit(i+2, "return", '')
ch = getch()
counterafter=i+3
token = symbol(a, stringsym, value=str(a)) # simplistic SINGLE DIGIT Ascii to Binary
# printMsg()
return
elif ch == "<":
ch = getch()
if ch == "=":
lt = ""
lt = "<" + "="
token = symbol(lt, lessthanequal, value=str(lt)) # simplistic SINGLE DIGIT Ascii to Binary
return
else:
ch == ungetch()
token = symbol("<", lessthan, value="<") # simplistic SINGLE DIGIT Ascii to Binary
return
elif ch == "!":
ne = ""
ch = getch()
if ch == "=":
ne = "!" + "="
token = symbol(ne, jumpne, value=str(ne)) # simplistic SINGLE DIGIT Ascii to Binary
return
else:
ch == ungetch()
token = symbol("!", NOT , value="!") # simplistic SINGLE DIGIT Ascii to Binary
return
elif ch == "=":
eq = ""
ch = getch()
if ch == "=":
eq = "=" + "="
token = symbol(eq, jumpeq, value=str(eq)) # simplistic SINGLE DIGIT Ascii to Binary
return
else:
ch == ungetch()
token = symbol("=", assignsym, value="=") # simplistic SINGLE DIGIT Ascii to Binary
return
elif ch == ">":
gt = ""
ch = getch()
if ch == "=":
gt = ">" + "="
token = symbol(gt, greaterthanequal, value=str(gt)) # simplistic SINGLE DIGIT Ascii to Binary
return
else:
ch == ungetch()
token = symbol(">", greaterthan, value=">") # simplistic SINGLE DIGIT Ascii to Binary
return
else:
print "Unknown character -->%s<- decimal %d" % (ch, ord(ch))
sys.exit(1) # Abort Compilation
#======================================================================
# THE GRAMMAR
# <program> ::= { <id> ; <vars > <stmtlist> }
# <vars> ::= var { <id> ; } % DECLARATIONS
# <array> ::= [<expr>]
# <stmtlist> ::= <stmt> { ; <stmt> }
# <stmt> ::= print <id>
# <id> = <expr>
# <expr> ::= <term> { (+ | - ) <term> }
# <term> ::= <factor> { (*|/) factor}
# <factor> ::= [+/-] ID | Number | expression
#======================================================================
# Centralised Parser Error Message handler
#======================================================================
#===============================================================================
def error (msg):
#===============================================================================
print line
print "-" * charIndex, "^"
print("Error on %d - %s\n" % (number, msg))
printToken(token)
print("\n")
#===============================================================================
def emit (memadr, opcode, parameter):
#===============================================================================
"""EMIT CODE - Emit a of code with a Parameter
if first arg is zero - (the memory address), use and incr CODEPTR"""
global codeptr
if (memadr == 0):
memadr = codeptr
codeptr = codeptr + 1
print "%6d %-8s %-7s" % (memadr, opcode, parameter)
#======================================================================
# VARIABLE DECLARATIONS
# <vars> ::= V { <id> ; }
# <vars> ::= <id>[array]
#===============================================================================
def vars() :
#===============================================================================
ta = 0
tn = []
global varptr;
getoken();
if token.token == idsym:
ta = token.address
tn = token.name
getoken()
if token.token == leftsquarebrace:
getoken()
if token.token == number: #number
print("#The address for "+ str(tn)+ " are ")
symtbl[tn].address = varptr;
emit(0, "constant", varptr)
while (token.value != 0):
# print("#address at " + str(varptr))
emit(0, "constant", token.value)
varptr = varptr + 1
token.value= token.value-1
array()
elif token.token == idsym: #id
# getoken()
expression()
getoken()
if token.token == rightsquarebrace:
getoken()
else:
if ta != 0:
print("%c already declared\n", tn);
#assignStmt()
else:
symtbl[tn].address = varptr;
varptr = varptr + 1
# emit(0, "load", varptr)
if token.token == assignsym:
getoken()
expression()
if token.token == rightsquarebrace:
getoken()
if token.token == rightbracket:
getoken()
if token.token == comma:
vars()
if token.token == number:
emit(0, "loadv", token.value)
emit(0, "add", 11)
emit(0, "store", 1)
getoken()
elif token.token == leftbrace:
getoken()
elif token.token == semicolon : getoken()
else: error("comma or semicolon expected in declaration")
#===============================================================================
def array():
# [expression]
#===============================================================================
global array;
expression()
print("#End of array expression")
"""
emit(0, "jump", 60)
emit(60, "load", 11)
emit(61, "add", 12)
emit(62, "store", 1)
"""
#======================================================================
# STMTLIST
# <stmtlist> ::= <stmt> { ; <stmt> }
#===============================================================================
def stmtList():
#===============================================================================
stmt()
while (token.token != rightbrace):
stmt()
#======================================================================
# STMT
#===============================================================================
def stmt():
#===============================================================================
""" <stmt> ::= print <expression|string>| read <vars> | <id> = <expression> |
if <condition> <stmt> [else <stmt>]| while <condition> <stmt>|
<stmtList> | do <stmsList> forever | break | continue
"""
global codeptr
thisStmtAdr = codeptr # Jump DEMO - not part of Stmt
# if token.token == arraysym:
# array()
if token.token == vars:
expression()
elif token.token == ifsym:
ifStmt()
if token.token == elsesym:
elseStmt()
elif token.token == whilesym:
whileStmt()
elif token.token == stmtList:
stmtList()
elif token.token == printsym:
printStmt()
elif token.token == readsym:
readStmt()
elif token.token == dosym:
doStmt()
foreverStmt()
elif token.token == breaksym:
breakStmt()
elif token.token == continuesym:
continueStmt()
elif token.token == number:
expression()
elif token.token == idsym:
assignStmt()
elif token.token == functionsym:
function()
elif token.token == returnsym:
returnStmt()
elif token.token == stringsym:
# print(str(token.name))
printMsg()
getoken()
elif token.token == leftbracket or token.token == rightbracket or token.token == leftbrace or token.token == rightbrace or token.token == rightsquarebrace or token.token == assignsym:
getoken()
elif token.token == commentstr or token.token == breaksym:
# print(str(token.name))
getoken()
elif token.token == lessthan or token.token == greaterthan or token.token == lessthanequal or token.token == greaterthanequal or token.token == jumpeq or token.token == jumpne:
relational_op()
elif token.token == semicolon or token.token == comma:
getoken()
else:
error("Expected start of a statement")
# emit (0, "return", thisStmtAdr) Jump DEMO need in break program
#===============================================================================
def printStmt():
#===============================================================================
""" <printStmt> ::= print <expression|string>"""
global idaddress
getoken()# skip "print"
getoken()
if token.token == stringsym:
printMsg()
# emit(0, "writeint", 501)
if token.token == idsym:
emit(0, "writeint", 501)
else:
emit(0, "writeint", 501)
# emit(0, "writeint", 7)
#===============================================================================
def printMsg():
#===============================================================================
""" <printMsg> ::= printMsg <expression>"""
# print("#"+str(counterafter)+ " counterafter")
# print("#"+str(counterafter1)+ " counterafter1")
# if counterafter != 100:
# emit(0,"loadv",counterafter )
emit(0, "loadv", counterafter1)
emit(0, "store", 1)
emit(0, "call", 400)
emit(400, "load-Ind", 0)
emit(401, "jumpeq", 405)
emit(402, "writech",0)
emit(403, "increment", 1)
emit(404, "jump", 400)
emit(405, "return", '')
getoken()
#===============================================================================
def readStmt():
#===============================================================================
""" <readStmt> ::= read <vars>"""
getoken()
emit(0, "readint", 7)
emit(0, "load", 7)
emit(0, "store", 500)
getoken()
#===============================================================================
def assignStmt():
#===============================================================================
"""
<id> = <expression>
"""
global tokennum
global resultnum
global whichidentifier
whichidentifier = token.name # Remember which ID on Left
whichidaddress = token.address
# print("#whichidentifier: " +str(whichidentifier))
getoken() # Get token after identifier
if token.token == assignsym:
getoken()
elif token.token == leftsquarebrace:
vars()
elif token.token == leftbrace:
getoken()
elif token.token == jumpeq:
getoken()
elif token.token == jumpne:
getoken()
elif token.token == rightbracket:
getoken()
elif token.token == lessthanequal:
getoken()
elif token.token == idsym:
getoken()
elif token.token == leftbracket:
getoken()
elif token.token == comma:
getoken()
elif token.token == greaterthanequal:
getoken()
# elif token.token == idsym: factor()
else:
error("Expected = in assignment statement")
# print("#Store value")
expression()
passtoken = token.value
# print(str(tokennum))
symtbl[whichidentifier].value = tokennum
emit(0, "store", whichidaddress)
getoken()
# emit(0, "writeint", whichidaddress)
# print("#assign " + str(whichidentifier))
# print("#assign " + str(whichidaddress))
# Save result into LHS runtime address
# expression()
#===============================================================================
def ifStmt():
# if-then-else
#===============================================================================
""" <ifStmt> ::= if <expression>"""
print("#IFSmt")
getoken() # skip "if"
condition()
stmt()
#===============================================================================
def elseStmt():
# if-then-else
#===============================================================================
""" <elseStmt> ::= else <expression>"""
print("#ElseSmt")
# emit(200, "jump", 47) # less than 2 go to else
getoken()
stmt()
# emit(314, "jump", 22)
#===============================================================================
def whileStmt():
#===============================================================================
""" <whileStmt> ::= while (condition)statement"""
# emit(0, "load", 201)
emit(0, "store", 502)
getoken()
expression() # num>0
stmtList()
emit(0, "jump", 25)
#===============================================================================
def returnStmt():
#===============================================================================
emit(600,"add", 201)
emit(601,"store", 502)
emit(602,"return", '')
getoken()
#===============================================================================
def condition():
#===============================================================================
if token.token == notsym:
emit(0, "Not",'')
getoken()
conditionalexp()
#===============================================================================
def conditionalexp():
#===============================================================================
expression()
relational_op()
expression()
#===============================================================================
def relational_op():
#===============================================================================
if token.token == lessthan or token.token == greaterthan or token.token == lessthanequal or token.token == greaterthanequal or token.token == jumpne or token.token == jumpeq:
op = token # remember -
getoken() # skip past -
term()
if op.token == lessthan:
# emit(0, "load", 501)
emit(0, "compare", 500)
emit(0, "jumplt", 43)
elif op.token == greaterthan:
# emit(0, "load", 200)
emit(0, "compare", 500)
emit(0, "jumpgt", 43)
elif op.token == lessthanequal:
# emit(0, "load", 200)
emit(0, "compare", 500)
emit(0, "jumplt", 43)
emit(0, "jumpeq", 43)
# emit(300, "writeInt", 502)
elif op.token == greaterthanequal:
# emit(0, "load", 200)
emit(0, "compare", 500)
emit(0, "jumpgt", 43)
emit(0, "jumpeq", 43)
# emit(300, "writeInt", 502)
elif op.token == jumpne:
emit(0, "load", 205)
emit(0, "compare", 502)
emit(0, "jumpne", 310)
emit(0, "writeInt", 0)
emit(0, "halt", 0)
# emit(310, "writeInt", 502)
elif op.token == jumpeq:
emit(0, "load", 200)
emit(0, "compare", 502)
emit(0, "jumpeq", 29)
#===============================================================================
def expression():
#===============================================================================
"""
Leaves result in ACC at runtime
Use addresses 999 & 998 as Temporary variables
<expression> ::= <factor> { (+ | -) <factor> } <- wrong
<expression> ::= <term> { (+ | -) <term> }
"""
global whichidentifier
global idaddress
global idvalue
if whichidentifier == None:
getoken()
else:
idaddress = symtbl[whichidentifier].address
# print("#Identifier address " + str(idaddress))
"""
idvalue = symtbl[whichidentifier].value
print("#Identifier value " + str(idvalue))
"""
if token.token == leftbracket:
getoken()
term()
while token.token == plus or token.token == minus:
op = token # remember -
getoken() # skip past -
term()
if op.token == plus:
emit(0, "add", 501)
# emit(0, "store", 500)
# emit(0, "writeInt", 500)
elif op.token == minus: # Subtract - have to swap operand order
emit(0, "load", 501)
emit(0, "subtract", 1)
emit(0, "store", 501)
getoken()
term()
# print("term 1" + str(factor()))
## 1st start==============================================================================
while token.token == plus or token.token == minus:
op = token # remember -
getoken() # skip past -
# emit(0, "store", 997) # Save current result
term()
# print("term 2" + str(term))
# print("#whichidentifier " + whichidentifier)
if op.token == plus:
emit(0, "add", 502)
# emit(0, "store", 500)
# emit(0, "writeInt", 500)
elif op.token == minus: # Subtract - have to swap operand order
emit(0, "load", 500)
emit(0, "subtract", 1)
emit(0, "store", idaddress)
# emit(0, "writeInt", 501)
#===============================================================================
def term():
#===============================================================================
"""
term::= factor {(*|/) factor}
"""
global idaddress
factor()
while token.token == mpy or token.token == div:
op = token # remember -
getoken() # skip past -
factor()
if op.token == mpy:
emit(0, "mpy", 502)
# emit(0, "store", 205)
emit(0, "store", 502)
# emit(0, "store", 210)
while token.token == mpy:
op2 = token # remember -
getoken() # skip past -
factor()
emit(0, "mpy", 502)
# emit(0, "store", 205)
emit(0, "store", idaddress)
elif op.token == div:
emit(0, "load", 502)
emit(0, "div", 202)
emit(0, "store", 503)
#===============================================================================
def factor():
#===============================================================================
"""
# FACTOR() - leaves result in ACC at runtime
<factor> ::= [+|-] identifier | number | (expression)
"""
global tokennum
global whichidentifier
global idaddress
global idvalue
# [+|-] number
if token.token == plus:
getoken()
if token.token == number:
emit(0, "loadv", token.value)
emit(0, "store", 200 + token.value)
getoken()
# - (unary)
elif token.token == minus:
getoken()
if token.token == number:
emit(0, "loadv", 0-token.value)
emit(0, "store", 200 + token.value)
getoken()
elif token.token == number:
emit(0, "loadv", token.value)
emit(0, "store-ind", 0)
emit(0, "store", 1)
tokennum = token.value
getoken()
# identifier
elif token.token == idsym:
# print("#token address " + str(token.address))
# print("#token value " + str(token.value))
emit(0, "load", token.address)
getoken()
# (expression)
elif token.token == leftbracket:
expression()
elif token.token == lessthan or token.token == greaterthan or token.token == lessthanequal or token.token == greaterthanequal or token.token == jumpeq or token.token == jumpne:
relational_op()
elif token.token == stringsym: #################
print("#String: " + str(token.name))
# printMsg()
printStmt()
getoken()
elif token.token == commentstr or token.token == rightbracket or token.token == leftsquarebrace or token.token == rightsquarebrace:
# print ("#Comment: " + str(token.name))
getoken()
elif token.token == breaksym:
emit(0,"halt", 0)
elif token.token == semicolon or token.token == comma:
getoken()
elif token.token == leftbrace:
getoken()
elif token.token == rightbrace:
print("")
elif token.token == ifsym:
ifStmt()
elif token.token == printsym or token.token == returnsym or token.token == functionsym:
getoken()
else:
error("Start Of Factor Expected")
#===============================================================================
def function():
#===============================================================================
if token.token == functionsym:
getoken()
if token.token == idsym:
getoken()
if token.token == idsym:
getoken()
if token.token == varsym :
vars()
if token.token == declaresym :
vars()
if token.token == varsym :
vars()
if token.token == leftbrace:
getoken()
stmtList()
if token.token == rightbrace:
print ("#---Function Finished---")
#===============================================================================
def program():
#===============================================================================
if token.token == programsym:
getoken()
else: error("Program start with 'program' keyword")
if token.token == idsym:
getoken()
if token.token == semicolon:
getoken()
# else: error("Semicolon expected")
if token.token == declaresym :
vars()
if token.token == varsym :
vars()
if token.token == semicolon:
getoken()
if token.token == functionsym:
function()
if token.token == semicolon:
getoken()
if token.token == leftbrace:
getoken()
stmtList()
stmtList()
if token.token == rightbrace:
print "#***Compilation Finished****"
#======================================================================
def main():
#======================================================================
global line
global srcfile
global charIndex
initSymTbl()
with open("test.txt") as srcfile:
# out1file = open('output.obj','w')
line = srcfile.read()
# out1file.write("hello")
# print line
charIndex = 0
debugScanner = False
if debugScanner: # Scanner Test Routine - Read a line and display the tokens
getoken()
while token.token is not None: # Skeleton for testing Scanner
printToken(token)
# y = str(token)
# out1file.write(y)
getoken()
sys.exit(1)
else:
getoken() # Parse Program according to the grammar
program()
#===============================================================================
# Main Compiler starts here
#===============================================================================
print "#Microcompiler.py v0.2"
emit(0, "load", 9)
main()
"""
srcfile = open('tiny_1.txt', 'r')
lexer = shlex.shlex(srcfile)
for token in lexer:
print repr(token)
"""
# getoken()
#=======================================================================
# *** That's it folks - written by Giovanni Moretti - April 27, 2011 ***
#=======================================================================
| [
[
1,
0,
0.0008,
0.0008,
0,
0.66,
0,
540,
0,
1,
0,
0,
540,
0,
0
],
[
14,
0,
0.0025,
0.0008,
0,
0.66,
0.0172,
777,
1,
0,
0,
0,
0,
3,
0
],
[
8,
0,
0.0106,
0.0101,
0,
0... | [
"import re",
"__author__ = 'YeeHin Kwok'",
"\"\"\" Giovanni's MicroCompiler Demo\n\n<program> ::= { <id> ; <vars > <stmtlist> }\n<vars> ::= V { <id> ; } % DECLARATIONS\n\n<stmtlist> ::= <stmt> { ; <stmt> }\n<stmt> ::= P <id> | <id> = <expr>",... |
import re
__author__ = 'YeeHin Kwok'
""" Giovanni's MicroCompiler Demo
<program> ::= { <id> ; <vars > <stmtlist> }
<vars> ::= V { <id> ; } % DECLARATIONS
<stmtlist> ::= <stmt> { ; <stmt> }
<stmt> ::= P <id> | <id> = <expr>
<expr> ::= <factor> { (+ | -) <factor> } % No precedence
<factor> ::= ID | Number
"""
import sys
import shlex
#===============================================================================
# # Lexical Analyser - the "Scanner" - Define the TokenTypes
#===============================================================================
tokenNames = \
[ "unknownToken", "idsym", "assignsym", "leftbrace", "rightbrace",
"varsym", "semicolon", "whilesym", "leftbracket", "rightbracket",
"printsym", "ifsym", "equals", "lessthan", "greaterthan",
"number", "plus", "minus", "mpy", "div", "elsesym", "declaresym", "forsym", "andsym", "elifsym", "dosym", "returnsym","notsym",
"continuesym", "breaksym", "nonesym", "programsym", "functionsym", "leftsquarebrace", "rightsquarebrace",
"lessthanequal", "colon", "comma", "comment", "commentstr", "dot", " greaterthanequal", "jumpeq", "jumpne",
"andop", "orop", "quote ", "stringsym", "arraysym", "readsym", "endfile"]
# define the tokens as variables
unknownToken, idsym, assignsym, leftbrace, rightbrace, \
varsym, semicolon, whilesym, leftbracket, rightbracket, \
printsym, ifsym, equals, lessthan, greaterthan, \
number, plus, minus, mpy, div, elsesym, declaresym, forsym, andsym, elifsym, dosym, returnsym, notsym,\
continuesym, breaksym, nonesym, programsym, functionsym, leftsquarebrace, rightsquarebrace, \
lessthanequal, colon, comma, comment, commentstr, dot, greaterthanequal, jumpeq, jumpne, \
andop, orop, quote, stringsym, arraysym, readsym, endfile = range(0, len(tokenNames))
#===============================================================================
class symbol:
#===============================================================================
name = None # String representation
token = None; # Corresponding token
address = 0; # For variables, their runtime address
value = None # on defined for numbers
def __init__(self, name, token, value=0):
self.name = name
self.token = token
self.address = 0 # for identifiers, their address
self.value = value # for numbers, their value
symtbl = {}; # The Symbol Table, a dictionary of symbols indexed by name
#======================================================================
# GLOBALS for output of Lexical Analyser
# Set by each call to GeToken()
token = None; # A symbol
line = "\n" # the complex source file as a string
charIndex = 0 # the position in the source
linenumber = 0 # The current number
tokennum = 0
resultnum = 0
whichidentifier = None;
identifieraddress = 0;
i = 100
j = 100
counterafter = i
counterafter1 = j
EOF = chr(0)
#======================================================================
# Run Time Code Generation Variables
varptr = 500 # Arbitrary base address of memory for variables
codeptr = 10 # Address to output next instruction (for code)
#===============================================================================
# Symbol Table Management Routines
#===============================================================================
#===============================================================================
def addToSymTbl (name, token):
#===============================================================================
symtbl[name] = symbol(name, token) # Add a new symbol to the dictionary
return symtbl[name]
#===============================================================================
def lookup (thisName):
#===============================================================================
"# Find a given identifier in the Symbol Table, Return the symtbl entry"
if symtbl.has_key(thisName): # thisName has been seen before
return symtbl[thisName] # return the symtbl entry
else: return None
#===============================================================================
def initSymTbl():
#===============================================================================
"# Initialise Symbol Table, and preload reserved words"
addToSymTbl('var', varsym) # VAR
addToSymTbl('program', programsym)
addToSymTbl('function', functionsym)
addToSymTbl('while', whilesym) # WHILE
addToSymTbl('print', printsym) # PRINT
addToSymTbl('else', elsesym)
addToSymTbl('elif', elifsym)
addToSymTbl('if', ifsym)
addToSymTbl('declare', declaresym)
addToSymTbl('for', forsym)
addToSymTbl('None', nonesym)
addToSymTbl('continue', continuesym)
addToSymTbl('read', readsym) # READINT
addToSymTbl('do', dosym)
addToSymTbl('return', returnsym)
addToSymTbl('not', notsym)
# Now add symbols - NB only single character symbols are here
# multicharacter one like ">=" are still to do
addToSymTbl('=', assignsym)
addToSymTbl('#', comment)
addToSymTbl('<', lessthan)
addToSymTbl('>', greaterthan)
addToSymTbl('{', leftbrace)
addToSymTbl('}', rightbrace)
addToSymTbl('(', leftbracket)
addToSymTbl(')', rightbracket)
addToSymTbl('+', plus)
addToSymTbl('-', minus)
addToSymTbl(';', semicolon)
addToSymTbl('break', breaksym)
addToSymTbl('*', mpy)
addToSymTbl('/', div)
addToSymTbl('[', leftsquarebrace)
addToSymTbl(']', rightsquarebrace)
addToSymTbl(':', colon)
addToSymTbl(',', comma)
addToSymTbl('.', dot)
addToSymTbl('==', jumpeq)
addToSymTbl('!=', jumpne)
addToSymTbl('&&', andop)
addToSymTbl('||', orop)
addToSymTbl('"', quote)
addToSymTbl(EOF, endfile)
#===============================================================================
# Scanner Diagnostics
#===============================================================================
def printToken(tok):
#===============================================================================
" - display the specified token."
if tok.token == idsym:
print "Token = %10s, %-10s adr = %3d, val = %d" % \
(tokenNames[tok.token], tok.name, tok.address, tok.value)
elif tok.token == number:
print "Token = %10s %d" % (tokenNames[tok.token], tok.value)
else:
print "Token = %10s" % tokenNames[tok.token]
#==============================?=================================================
def dumpSymTbl():
#===============================================================================
""" Dump all the tokens in the symboltable """
print("# *** Symbol Table ***")
for name in symtbl.keys(): # keys is a list of the names (printable form of tokens)
tok = symtbl[name]
if tok.token == idsym:
print("#"),
printToken(tok)
#===============================================================================
def getch():
#===============================================================================
global line
global charIndex
global linenumber
while True:
if charIndex < len(line): # See if used up current line
ch = line[charIndex] # if not, get character
charIndex = charIndex + 1 # & move pointer for next time
else:
# line = f.readline()
# if line == "": line = EOF
dumpSymTbl()
print "#End of File"
print "#--> ",
line = raw_input() + "\n" # read new line, adding \n so it's like f.readline()
# line = srcfile.read()
charIndex = 0 # & reset character pointer
linenumber = linenumber + 1
continue
if ch == "\n":
ch = " "
if ch == '?':
dumpSymTbl()
continue
return ch
#===============================================================================
def ungetch():
#===============================================================================
""" Unget the next character peeked at when building variables, numbers
and when distinguishing between >= and > ...
"""
global charIndex;
charIndex = charIndex - 1;
#===============================================================================
def getoken():
#===============================================================================
""" GETOKEN - Put next token into the global TOKEN """
global token
global i
global m
global counterafter
global counterafter1
x = 0
ch = getch() # skip whitespace
while ch in ["\t", " ", "\n"]:
ch = getch()
# If ch is alphabetic then this is start of reserved word or an identifier
if ch.isalpha(): # Letter therefore it's either identifier or reserved word
name = ""
while ch.isalpha() or ch.isdigit() or ch == "_":
name = name + ch
ch = getch()
ungetch() # let terminator be used next time
token = lookup(name) # See if token's known
if token is None: # if not
token = addToSymTbl(name, idsym) # add as 'idsym'-IDENTIFIER
return # we've set token.token to either id or tokentype of reserved word
elif ch in ["{", "}", "(", ")", "[", "]", "+", "-", "*", "/", ";", ",", ":", EOF]:
token = lookup(ch) # preloaded with appropriate token
elif ch.isdigit():
# In the real version, build number and don't forget to end with ungetch()
while(ch.isdigit() == True):
x = str(x) + str(ch)
ch = getch()
ch = ungetch()
token = symbol(x, number, value=int(x)) # simplistic SINGLE DIGIT Ascii to Binary
return
# elif ch == "-":
# x = ""
# no =""
# ch = getch()
# if ch.isdigit() ==True:
# while ch.isdigit():
# x = str(x) + str(ch)
# ch = getch()
#
# ch = ungetch()
#
# no = "-" + str(x)
#
# token = symbol(no, number, value = int(no))
elif ch == '#':
str1 = ""
ch = getch()
while(ch != " "):
str1 = str(str1) + str(ch)
ch = getch()
ch = getch()
token = symbol(str1, commentstr, value=str(str1)) # simplistic SINGLE DIGIT Ascii to Binary
print("#comment: " + str(str1))
return
elif ch == '"':
a = ""
ch = getch()
counterafter1 =counterafter
i=counterafter
if counterafter != 100:
counterafter=counterafter+4;
counterafter = i
while (ch != '"'):
a = str(a) + str(ch)
if ch != " ":
b = "'"+ch+"'"
emit(i, "constant",b)
ch = getch()
i=i+1
emit(i, "constant", 13)
emit(i+1, "constant", 0)
# emit(i+2, "writech", '')
emit(i+2, "return", '')
ch = getch()
counterafter=i+3
token = symbol(a, stringsym, value=str(a)) # simplistic SINGLE DIGIT Ascii to Binary
# printMsg()
return
elif ch == "<":
ch = getch()
if ch == "=":
lt = ""
lt = "<" + "="
token = symbol(lt, lessthanequal, value=str(lt)) # simplistic SINGLE DIGIT Ascii to Binary
return
else:
ch == ungetch()
token = symbol("<", lessthan, value="<") # simplistic SINGLE DIGIT Ascii to Binary
return
elif ch == "!":
ne = ""
ch = getch()
if ch == "=":
ne = "!" + "="
token = symbol(ne, jumpne, value=str(ne)) # simplistic SINGLE DIGIT Ascii to Binary
return
else:
ch == ungetch()
token = symbol("!", NOT , value="!") # simplistic SINGLE DIGIT Ascii to Binary
return
elif ch == "=":
eq = ""
ch = getch()
if ch == "=":
eq = "=" + "="
token = symbol(eq, jumpeq, value=str(eq)) # simplistic SINGLE DIGIT Ascii to Binary
return
else:
ch == ungetch()
token = symbol("=", assignsym, value="=") # simplistic SINGLE DIGIT Ascii to Binary
return
elif ch == ">":
gt = ""
ch = getch()
if ch == "=":
gt = ">" + "="
token = symbol(gt, greaterthanequal, value=str(gt)) # simplistic SINGLE DIGIT Ascii to Binary
return
else:
ch == ungetch()
token = symbol(">", greaterthan, value=">") # simplistic SINGLE DIGIT Ascii to Binary
return
else:
print "Unknown character -->%s<- decimal %d" % (ch, ord(ch))
sys.exit(1) # Abort Compilation
#======================================================================
# THE GRAMMAR
# <program> ::= { <id> ; <vars > <stmtlist> }
# <vars> ::= var { <id> ; } % DECLARATIONS
# <array> ::= [<expr>]
# <stmtlist> ::= <stmt> { ; <stmt> }
# <stmt> ::= print <id>
# <id> = <expr>
# <expr> ::= <term> { (+ | - ) <term> }
# <term> ::= <factor> { (*|/) factor}
# <factor> ::= [+/-] ID | Number | expression
#======================================================================
# Centralised Parser Error Message handler
#======================================================================
#===============================================================================
def error (msg):
#===============================================================================
print line
print "-" * charIndex, "^"
print("Error on %d - %s\n" % (number, msg))
printToken(token)
print("\n")
#===============================================================================
def emit (memadr, opcode, parameter):
#===============================================================================
"""EMIT CODE - Emit a of code with a Parameter
if first arg is zero - (the memory address), use and incr CODEPTR"""
global codeptr
if (memadr == 0):
memadr = codeptr
codeptr = codeptr + 1
print "%6d %-8s %-7s" % (memadr, opcode, parameter)
#======================================================================
# VARIABLE DECLARATIONS
# <vars> ::= V { <id> ; }
# <vars> ::= <id>[array]
#===============================================================================
def vars() :
#===============================================================================
ta = 0
tn = []
global varptr;
getoken();
if token.token == idsym:
ta = token.address
tn = token.name
getoken()
if token.token == leftsquarebrace:
getoken()
if token.token == number: #number
print("#The address for "+ str(tn)+ " are ")
symtbl[tn].address = varptr;
emit(0, "constant", varptr)
while (token.value != 0):
# print("#address at " + str(varptr))
emit(0, "constant", token.value)
varptr = varptr + 1
token.value= token.value-1
array()
elif token.token == idsym: #id
# getoken()
expression()
getoken()
if token.token == rightsquarebrace:
getoken()
else:
if ta != 0:
print("%c already declared\n", tn);
#assignStmt()
else:
symtbl[tn].address = varptr;
varptr = varptr + 1
# emit(0, "load", varptr)
if token.token == assignsym:
getoken()
expression()
if token.token == rightbracket:
getoken()
if token.token == comma:
vars()
elif token.token == semicolon : getoken()
else: error("comma or semicolon expected in declaration")
#===============================================================================
def array():
# [expression]
#===============================================================================
global array;
expression()
#===============================================================================
def parameters():
#===============================================================================
vars()
#======================================================================
# STMTLIST
# <stmtlist> ::= <stmt> { ; <stmt> }
#===============================================================================
def stmtList():
#===============================================================================
stmt()
while (token.token != rightbrace):
stmt()
#======================================================================
# STMT
#===============================================================================
def stmt():
#===============================================================================
""" <stmt> ::= print <expression|string>| read <vars> | <id> = <expression> |
if <condition> <stmt> [else <stmt>]| while <condition> <stmt>|
<stmtList> | do <stmsList> forever | break | continue
"""
global codeptr
thisStmtAdr = codeptr # Jump DEMO - not part of Stmt
# if token.token == arraysym:
# array()
if token.token == vars:
expression()
if token.token == ifsym:
ifStmt()
if token.token == elsesym:
elseStmt()
elif token.token == whilesym:
whileStmt()
elif token.token == stmtList:
stmtList()
elif token.token == printsym:
printStmt()
elif token.token == readsym:
readStmt()
elif token.token == dosym:
doStmt()
foreverStmt()
elif token.token == breaksym:
factor()
elif token.token == continuesym:
continueStmt()
elif token.token == number:
expression()
elif token.token == idsym:
assignStmt()
elif token.token == functionsym:
function()
elif token.token == returnsym:
returnStmt()
elif token.token == stringsym:
# print(str(token.name))
printMsg()
getoken()
elif token.token == leftbracket or token.token == rightbracket or token.token == leftbrace or token.token == rightbrace or token.token == rightsquarebrace or token.token == assignsym:
getoken()
elif token.token == commentstr or token.token == breaksym:
# print(str(token.name))
getoken()
elif token.token == lessthan or token.token == greaterthan or token.token == lessthanequal or token.token == greaterthanequal or token.token == jumpeq or token.token == jumpne:
relational_op()
elif token.token == semicolon or token.token == comma:
getoken()
else:
error("Expected start of a statement")
# emit (0, "return", thisStmtAdr) Jump DEMO need in break program
#===============================================================================
def printStmt():
#===============================================================================
""" <printStmt> ::= print <expression|string>"""
global idaddress
getoken()# skip "print"
getoken()
if token.token == stringsym:
printMsg()
# emit(0, "writeint", 501)
if token.token == idsym:
emit(0, "writeint", 501)
emit(0, "halt", '')
else:
emit(0, "writeint", 501)
# emit(0, "writeint", 7)
#===============================================================================
def printMsg():
#===============================================================================
""" <printMsg> ::= printMsg <expression>"""
# print("#"+str(counterafter)+ " counterafter")
# print("#"+str(counterafter1)+ " counterafter1")
emit(0, "loadv", counterafter1)
emit(0, "store", 1)
emit(0, "call", 400)
emit(400, "load-Ind", 0)
emit(401, "jumpeq", 405)
emit(402, "writech",0)
emit(403, "increment", 1)
emit(404, "jump", 400)
emit(405, "return", '')
getoken()
#===============================================================================
def readStmt():
#===============================================================================
""" <readStmt> ::= read <vars>"""
getoken()
emit(0, "readint", 7)
emit(0, "load", 7)
emit(0, "store", 500)
getoken()
#===============================================================================
def assignStmt():
#===============================================================================
"""
<id> = <expression>
"""
global tokennum
global resultnum
global whichidentifier
whichidentifier = token.name # Remember which ID on Left
whichidaddress = token.address
# print("#whichidentifier: " +str(whichidentifier))
getoken() # Get token after identifier
if token.token == assignsym:
getoken()
elif token.token == leftsquarebrace:
vars()
elif token.token == leftbrace:
vars()
elif token.token == jumpeq:
getoken()
elif token.token == jumpne:
getoken()
elif token.token == rightbracket:
getoken()
elif token.token == lessthanequal:
getoken()
elif token.token == idsym:
getoken()
elif token.token == leftbracket:
getoken()
elif token.token == comma:
getoken()
elif token.token == greaterthanequal:
getoken()
# elif token.token == idsym: factor()
else:
error("Expected = in assignment statement")
# print("#Store value")
expression()
passtoken = token.value
# print(str(tokennum))
symtbl[whichidentifier].value = tokennum
emit(0, "store", whichidaddress)
getoken()
#===============================================================================
def ifStmt():
# if-then-else
#===============================================================================
""" <ifStmt> ::= if <expression>"""
print("#IFSmt")
getoken() # skip "if"
condition()
stmt()
#===============================================================================
def elseStmt():
# if-then-else
#===============================================================================
""" <elseStmt> ::= else <expression>"""
print("#ElseSmt")
# emit(200, "jump", 47) # less than 2 go to else
getoken()
stmt()
# emit(0, "halt", '')
#===============================================================================
def whileStmt():
#===============================================================================
""" <whileStmt> ::= while (condition)statement"""
# emit(0, "load", 201)
emit(0, "store", 502)
getoken()
expression() # num>0
stmtList()
emit(0, "jump", 28)
#===============================================================================
def returnStmt():
#===============================================================================
getoken()
if token.token == leftbracket:
getoken()
if token.token == idsym:
emit(600, "add", 504)
emit(601, "store", 503)
emit(602, "return", '')
if token.token == rightbracket:
getoken()
if token.token == semicolon:
getoken()
#===============================================================================
def condition():
#===============================================================================
if token.token == notsym:
emit(0, "Not",'')
getoken()
conditionalexp()
#===============================================================================
def conditionalexp():
#===============================================================================
expression()
relational_op()
expression()
#===============================================================================
def relational_op():
#===============================================================================
if token.token == lessthan or token.token == greaterthan or token.token == lessthanequal or token.token == greaterthanequal or token.token == jumpne or token.token == jumpeq:
op = token # remember -
getoken() # skip past -
term()
if op.token == lessthan:
# emit(0, "load", 501)
emit(0, "compare", 500)
emit(0, "jumplt", 46)
elif op.token == greaterthan:
# emit(0, "load", 200)
emit(0, "compare", 500)
emit(0, "jumpgt", 46)
elif op.token == lessthanequal:
# emit(0, "load", 200)
emit(0, "compare", 500)
emit(0, "jumplt", 46)
emit(0, "jumpeq", 46)
# emit(300, "writeInt", 502)
elif op.token == greaterthanequal:
# emit(0, "load", 200)
emit(0, "compare", 500)
emit(0, "jumpgt", 46)
emit(0, "jumpeq", 46)
# emit(300, "writeInt", 502)
elif op.token == jumpne:
emit(0, "load", 205)
emit(0, "compare", 502)
emit(0, "jumpne", 310)
emit(0, "writeInt", 0)
emit(0, "halt", 0)
# emit(310, "writeInt", 502)
elif op.token == jumpeq:
# emit(0, "load", 200)
emit(0, "compare", 501)
emit(0, "jumpeq", 52)
emit(0, "jump", 57)
#===============================================================================
def expression():
#===============================================================================
"""
Leaves result in ACC at runtime
Use addresses 999 & 998 as Temporary variables
<expression> ::= <factor> { (+ | -) <factor> } <- wrong
<expression> ::= <term> { (+ | -) <term> }
"""
global whichidentifier
global idaddress
global idvalue
idaddress = symtbl[whichidentifier].address
if token.token == leftbracket:
getoken()
term()
while token.token == plus or token.token == minus:
op = token # remember -
getoken() # skip past -
term()
if op.token == plus:
emit(0, "add", 501)
# emit(0, "store", 500)
# emit(0, "writeInt", 500)
elif op.token == minus: # Subtract - have to swap operand order
emit(0, "load", 501)
emit(0, "subtract", 1)
emit(0, "store", 501)
getoken()
term()
# print("term 1" + str(factor()))
## 1st start==============================================================================
while token.token == plus or token.token == minus:
op = token # remember -
getoken() # skip past -
# emit(0, "store", 997) # Save current result
term()
# print("term 2" + str(term))
# print("#whichidentifier " + whichidentifier)
if op.token == plus:
emit(0, "add", 502)
# emit(0, "store", 500)
# emit(0, "writeInt", 500)
elif op.token == minus: # Subtract - have to swap operand order
emit(0, "load", 500)
emit(0, "subtract", 1)
emit(0, "store", idaddress)
# emit(0, "writeInt", 501)
#===============================================================================
def term():
#===============================================================================
"""
term::= factor {(*|/) factor}
"""
global idaddress
factor()
while token.token == mpy or token.token == div:
op = token # remember -
getoken() # skip past -
factor()
if op.token == mpy:
emit(0, "mpy", 502)
# emit(0, "store", 205)
emit(0, "store", 502)
# emit(0, "store", 210)
while token.token == mpy:
op2 = token # remember -
getoken() # skip past -
factor()
emit(0, "mpy", 502)
# emit(0, "store", 205)
emit(0, "store", idaddress)
elif op.token == div:
emit(0, "load", 502)
emit(0, "div", 202)
emit(0, "store", 503)
#===============================================================================
def factor():
#===============================================================================
"""
# FACTOR() - leaves result in ACC at runtime
<factor> ::= [+|-] identifier | number | (expression)
"""
global tokennum
global whichidentifier
global idaddress
global idvalue
# [+|-] number
if token.token == plus:
getoken()
if token.token == number:
emit(0, "loadv", token.value)
emit(0, "store", 200 + token.value)
getoken()
# - (unary)
elif token.token == minus:
getoken()
if token.token == number:
emit(0, "loadv", 0-token.value)
emit(0, "store", 200 + token.value)
getoken()
elif token.token == number:
emit(0, "loadv", token.value)
emit(0, "store", 1)
tokennum = token.value
getoken()
# identifier
elif token.token == idsym:
# print("#token address " + str(token.address))
# print("#token value " + str(token.value))
emit(0, "load", token.address)
getoken()
# (expression)
elif token.token == leftbracket:
expression()
elif token.token == lessthan or token.token == greaterthan or token.token == lessthanequal or token.token == greaterthanequal or token.token == jumpeq or token.token == jumpne:
relational_op()
elif token.token == stringsym: #################
print("#String: " + str(token.name))
# printMsg()
printStmt()
getoken()
elif token.token == commentstr or token.token == rightbracket or token.token == leftsquarebrace or token.token == rightsquarebrace:
# print ("#Comment: " + str(token.name))
getoken()
elif token.token == breaksym:
emit(0,"halt", 0)
getoken()
elif token.token == semicolon or token.token == comma:
getoken()
elif token.token == leftbrace:
getoken()
elif token.token == rightbrace:
print("")
elif token.token == ifsym:
ifStmt()
elif token.token == printsym or token.token == returnsym or token.token == functionsym:
getoken()
else:
error("Start Of Factor Expected")
"""
elif token.token == assignsym:
getoken()
elif token.token == lessthanequal:
getoken()
elif token.token == greaterthanequal:
getoken()
elif token.token == jumpeq:
getoken()
"""
#===============================================================================
def function():
#===============================================================================
if token.token == functionsym:
getoken()
if token.token == idsym:
getoken()
if token.token == leftbracket:
getoken()
if token.token == idsym:
parameters()
elif token.token == number:
print("#"+str(token.value))
emit(0, "loadv", token.value)
emit(0, "call", 600)
getoken()
else:
error("Function error : No_parameter_input_for_function")
if token.token == rightbracket:
getoken()
if token.token == declaresym :
vars()
if token.token == varsym :
vars()
if token.token == semicolon:
getoken()
if token.token == leftbrace:
getoken()
if token.token == plus:
expression
getoken()
stmt()
# emit(0, "call", 600)
# returnStmt()
# emit(0, "call", 600)
if token.token == semicolon:
getoken()
if token.token == rightbrace:
print ("#---Function Finished---")
#===============================================================================
def program():
#===============================================================================
if token.token == leftbrace:
getoken()
if token.token == programsym:
getoken()
else: error("Program start with 'program' keyword")
if token.token == idsym:
getoken()
if token.token == semicolon:
getoken()
if token.token == declaresym :
vars()
if token.token == varsym :
vars()
if token.token == functionsym:
function()
if token.token == leftbrace:
getoken()
stmtList()
stmtList()
if token.token == rightbrace:
print "#***Compilation Finished****"
#======================================================================
def main():
#======================================================================
global line
global srcfile
global charIndex
initSymTbl()
with open("string.txt") as srcfile:
# out1file = open('output.obj','w')
line = srcfile.read()
# out1file.write("hello")
# print line
charIndex = 0
debugScanner = False
if debugScanner: # Scanner Test Routine - Read a line and display the tokens
getoken()
while token.token is not None: # Skeleton for testing Scanner
printToken(token)
# y = str(token)
# out1file.write(y)
getoken()
sys.exit(1)
else:
getoken() # Parse Program according to the grammar
program()
#===============================================================================
# Main Compiler starts here
#===============================================================================
print "#Microcompiler.py v0.2"
emit(0, "load", 9)
main()
# emit(0, "constant", "'A'") #need in break,comment,exitloop,writer-if-read-write-ch program
# emit(0, "constant", 10)
# emit(0, "constant", 12)
# emit(0, "constant", 25)
# emit(0, "constant", -10)
"""
srcfile = open('tiny_1.txt', 'r')
lexer = shlex.shlex(srcfile)
for token in lexer:
print repr(token)
"""
# getoken()
#=======================================================================
# *** That's it folks - written by Giovanni Moretti - April 27, 2011 ***
#=======================================================================
| [
[
1,
0,
0.0008,
0.0008,
0,
0.66,
0,
540,
0,
1,
0,
0,
540,
0,
0
],
[
14,
0,
0.0025,
0.0008,
0,
0.66,
0.0169,
777,
1,
0,
0,
0,
0,
3,
0
],
[
8,
0,
0.0105,
0.01,
0,
0.6... | [
"import re",
"__author__ = 'YeeHin Kwok'",
"\"\"\" Giovanni's MicroCompiler Demo\n\n<program> ::= { <id> ; <vars > <stmtlist> }\n<vars> ::= V { <id> ; } % DECLARATIONS\n\n<stmtlist> ::= <stmt> { ; <stmt> }\n<stmt> ::= P <id> | <id> = <expr>",... |
import re
__author__ = 'YeeHin Kwok'
""" MicroCompiler
<program> ::= program <id>; declare declareList; { StmtList}
<declareList> ::= varDeclare {, varDeclare};
<varDeclare> ::= idsym [ = number | "[" number "]"
<stmt> ::= variable( = expression | parameter) | <printStmt> ::= print "("<print_item>{,<print_item>}")"| if <condition> <stmt> [else <stmt>]|
<readStmt> ::= read "("variable")" | <id> = <expression> |
while <condition> <stmt>| <stmtList> | do <stmsList> forever | break | continue
<stmtlist> ::= <stmt> { ; <stmt> }
<print_item> ::= expression | string
<condition> ::= [not] <conditionalexp>
<conditionalexp> ::= <expression>[<relational_op> <expression>]
<relational_op> ::= <|<=|==|!=|>|>=
<expression> ::= <term> { (+ | -) <term> }
<term> ::= <factor> {(*|/) <factor>}
<factor> ::= [+|-] <id> | <number> | "("<expression>")"
<variable> ::= <id> [<arraySub>]
<arraySub> ::= "["<expression>"]"
<constnat> ::= <number>
<id> ::= A-Z{A-Z _ 0-9 ? }
"""
import sys
import shlex
#===============================================================================
# # Lexical Analyser - the "Scanner" - Define the TokenTypes
#===============================================================================
tokenNames = \
[ "unknownToken", "idsym", "assignsym", "leftbrace", "rightbrace",
"varDeclareym", "semicolon", "whilesym", "leftbracket", "rightbracket",
"printsym", "ifsym", "equals", "lessthan", "greaterthan",
"number", "plus", "minus", "mpy", "div", "elsesym", "declaresym", "forsym", "andsym", "elifsym", "dosym", "returnsym", "notsym",
"continuesym", "breaksym", "nonesym", "programsym", "functionsym", "leftsquarebracket", "rightsquarebracket",
"lessthanequal", "colon", "comma", "comment", "commentstr", "dot", " greaterthanequal", "jumpeq", "jumpne",
"andop", "orop", "quote ", "stringsym", "arraySubsym", "readsym", "endfile"]
# define the tokens as variables
unknownToken, idsym, assignsym, leftbrace, rightbrace, \
varDeclareym, semicolon, whilesym, leftbracket, rightbracket, \
printsym, ifsym, equals, lessthan, greaterthan, \
number, plus, minus, mpy, div, elsesym, declaresym, forsym, andsym, elifsym, dosym, returnsym, notsym, \
continuesym, breaksym, nonesym, programsym, functionsym, leftsquarebracket, rightsquarebracket, \
lessthanequal, colon, comma, comment, commentstr, dot, greaterthanequal, jumpeq, jumpne, \
andop, orop, quote, stringsym, arraySubsym, readsym, endfile = range(0, len(tokenNames))
#===============================================================================
class symbol:
#===============================================================================
name = None # String representation
token = None; # Corresponding token
address = 0; # For variables, their runtime address
value = None # on defined for numbers
def __init__(self, name, token, value=0):
self.name = name
self.token = token
self.address = 0 # for identifiers, their address
self.value = value # for numbers, their value
symtbl = {}; # The Symbol Table, a dictionary of symbols indexed by name
#======================================================================
# GLOBALS for output of Lexical Analyser
# Set by each call to GeToken()
token = None; # A symbol
line = "\n" # the complex source file as a string
charIndex = 0 # the position in the source
linenumber = 0 # The current number
tokennum = 0
whichidentifier = None;
arraySubaddress = 0;
endaddress = 0;
i = 700
j = 700
counterafter = i
counterafter1 = j
EOF = chr(0)
#======================================================================
# Run Time Code Generation Variables
varptr = 500 # Arbitrary base address of memory for variables
codeptr = 10 # Address to output next instruction (for code)
#===============================================================================
# Symbol Table Management Routines
#===============================================================================
#===============================================================================
def addToSymTbl (name, token):
#===============================================================================
symtbl[name] = symbol(name, token) # Add a new symbol to the dictionary
return symtbl[name]
#===============================================================================
def lookup (thisName):
#===============================================================================
"# Find a given identifier in the Symbol Table, Return the symtbl entry"
if symtbl.has_key(thisName): # thisName has been seen before
return symtbl[thisName] # return the symtbl entry
else: return None
#===============================================================================
def initSymTbl():
#===============================================================================
"# Initialise Symbol Table, and preload reserved words"
addToSymTbl('var', varDeclareym) # VAR
addToSymTbl('program', programsym)
addToSymTbl('function', functionsym)
addToSymTbl('while', whilesym) # WHILE
addToSymTbl('print', printsym) # PRINT
addToSymTbl('else', elsesym)
addToSymTbl('elif', elifsym)
addToSymTbl('if', ifsym)
addToSymTbl('declare', declaresym)
addToSymTbl('for', forsym)
addToSymTbl('None', nonesym)
addToSymTbl('continue', continuesym)
addToSymTbl('read', readsym) # READINT
addToSymTbl('do', dosym)
addToSymTbl('return', returnsym)
addToSymTbl('not', notsym)
# Now add symbols - NB only single character symbols are here
# multicharacter one like ">=" are still to do
addToSymTbl('=', assignsym)
addToSymTbl('#', comment)
addToSymTbl('<', lessthan)
addToSymTbl('>', greaterthan)
addToSymTbl('{', leftbrace)
addToSymTbl('}', rightbrace)
addToSymTbl('(', leftbracket)
addToSymTbl(')', rightbracket)
addToSymTbl('+', plus)
addToSymTbl('-', minus)
addToSymTbl(';', semicolon)
addToSymTbl('break', breaksym)
addToSymTbl('*', mpy)
addToSymTbl('/', div)
addToSymTbl('[', leftsquarebracket)
addToSymTbl(']', rightsquarebracket)
addToSymTbl(':', colon)
addToSymTbl(',', comma)
addToSymTbl('.', dot)
addToSymTbl('==', jumpeq)
addToSymTbl('!=', jumpne)
addToSymTbl('&&', andop)
addToSymTbl('||', orop)
addToSymTbl('"', quote)
addToSymTbl(EOF, endfile)
#===============================================================================
# Scanner Diagnostics
#===============================================================================
def printToken(tok):
#===============================================================================
" - display the specified token."
if tok.token == idsym:
print "Token = %10s, %-10s adr = %3d, val = %d" % \
(tokenNames[tok.token], tok.name, tok.address, tok.value)
elif tok.token == number:
print "Token = %10s %d" % (tokenNames[tok.token], tok.value)
else:
print "Token = %10s" % tokenNames[tok.token]
#==============================?=================================================
def dumpSymTbl():
#===============================================================================
""" Dump all the tokens in the symboltable """
print("# *** Symbol Table ***")
for name in symtbl.keys(): # keys is a list of the names (printable form of tokens)
tok = symtbl[name]
if tok.token == idsym:
print("#"),
printToken(tok)
#===============================================================================
def getch():
#===============================================================================
global line
global charIndex
global linenumber
while True:
if charIndex < len(line): # See if used up current line
ch = line[charIndex] # if not, get character
charIndex = charIndex + 1 # & move pointer for next time
else:
# line = f.readline()
# if line == "": line = EOF
dumpSymTbl()
print "#End of File"
print "#--> ",
line = raw_input() + "\n" # read new line, adding \n so it's like f.readline()
# line = srcfile.read()
charIndex = 0 # & reset character pointer
linenumber = linenumber + 1
continue
if ch == "\n":
ch = " "
if ch == '?':
dumpSymTbl()
continue
return ch
#===============================================================================
def ungetch():
#===============================================================================
""" Unget the next character peeked at when building variables, numbers
and when distinguishing between >= and > ...
"""
global charIndex;
charIndex = charIndex - 1;
#===============================================================================
def getoken():
#===============================================================================
""" GETOKEN - Put next token into the global TOKEN """
global token
global i
global m
global counterafter
global counterafter1
x = 0
ch = getch() # skip whitespace
while ch in ["\t", " ", "\n"]:
ch = getch()
# If ch is alphabetic then this is start of reserved word or an identifier
if ch.isalpha(): # Letter therefore it's either identifier or reserved word
name = ""
while ch.isalpha() or ch.isdigit() or ch == "_":
name = name + ch
ch = getch()
ungetch() # let terminator be used next time
token = lookup(name) # See if token's known
if token is None: # if not
token = addToSymTbl(name, idsym) # add as 'idsym'-IDENTIFIER
return # we've set token.token to either id or tokentype of reserved word
elif ch in ["{", "}", "(", ")", "[", "]", "+", "-", "*", "/", ";", ",", ":", EOF]:
token = lookup(ch) # preloaded with appropriate token
elif ch.isdigit():
# In the real version, build number and don't forget to end with ungetch()
while(ch.isdigit() == True):
x = str(x) + str(ch)
ch = getch()
ch = ungetch()
token = symbol(x, number, value=int(x)) # simplistic SINGLE DIGIT Ascii to Binary
return
# If ch is #
elif ch == '#':
str1 = ""
ch = getch()
#End while if the comment have ""
while ch != " ":
str1 = str(str1) + str(ch)
ch = getch()
ch = getch()
print("#comment: " + str(str1))
return
# If ch is "
elif ch == '"':
a = ""
ch = getch()
counterafter1 = counterafter
i = counterafter
if counterafter != 700:
counterafter = counterafter + 4;
counterafter = i
while (ch != '"'):
a = str(a) + str(ch)
if ch != " ":
b = "'" + ch + "'"
emit(i, "constant", b)
ch = getch()
else:
ch = getch()
i = i + 1
emit(i, "constant", 13)
emit(i + 1, "constant", 0)
emit(i + 2, "return", '')
ch = getch()
counterafter = i + 3
token = symbol(a, stringsym, value=str(a)) # simplistic SINGLE DIGIT Ascii to Binary
return
# If ch is <
elif ch == "<":
ch = getch()
if ch == "=":
lt = ""
lt = "<" + "="
token = symbol(lt, lessthanequal, value=str(lt)) # simplistic SINGLE DIGIT Ascii to Binary
return
else:
ch == ungetch()
token = symbol("<", lessthan, value="<") # simplistic SINGLE DIGIT Ascii to Binary
return
# If ch is !
elif ch == "!":
ne = ""
ch = getch()
if ch == "=":
ne = "!" + "="
token = symbol(ne, jumpne, value=str(ne)) # simplistic SINGLE DIGIT Ascii to Binary
return
else:
ch == ungetch()
token = symbol("!", NOT , value="!") # simplistic SINGLE DIGIT Ascii to Binary
return
# If ch is =
elif ch == "=":
eq = ""
ch = getch()
if ch == "=":
eq = "=" + "="
token = symbol(eq, jumpeq, value=str(eq)) # simplistic SINGLE DIGIT Ascii to Binary
return
else:
ch == ungetch()
token = symbol("=", assignsym, value="=") # simplistic SINGLE DIGIT Ascii to Binary
return
# If ch is >
elif ch == ">":
gt = ""
ch = getch()
if ch == "=":
gt = ">" + "="
token = symbol(gt, greaterthanequal, value=str(gt)) # simplistic SINGLE DIGIT Ascii to Binary
return
else:
ch == ungetch()
token = symbol(">", greaterthan, value=">") # simplistic SINGLE DIGIT Ascii to Binary
return
else:
print "Unknown character -->%s<- decimal %d" % (ch, ord(ch))
sys.exit(1) # Abort Compilation
#======================================================================
# THE GRAMMAR
# <program> ::= program <id>; declare declareList; { StmtList}
# <declareList> ::= varDeclare {, varDeclare};
# <varDeclare> ::= idsym [ = number | "[" number "]"
# <stmt> ::= variable( = expression | parameter) | <printStmt> ::= print "("<print_item>{,<print_item>}")"| if <condition> <stmt> [else <stmt>]|
# <readStmt> ::= read "("variable")" | <id> = <expression> |
# while <condition> <stmt>| <stmtList> | do <stmsList> forever | break | continue
# <stmtlist> ::= <stmt> { ; <stmt> }
# <print_item> ::= expression | string
# <condition> ::= [not] <conditionalexp>
# <conditionalexp> ::= <expression>[<relational_op> <expression>]
# <relational_op> ::= <|<=|==|!=|>|>=
# <expression> ::= <term> { (+ | -) <term> }
# <term> ::= <factor> {(*|/) <factor>}
# <factor> ::= [+|-] <id> | <number> | "("<expression>")"
# <variable> ::= <id> [<arraySub>]
# <arraySub> ::= "["<expression>"]"
#======================================================================
# Centralised Parser Error Message handler
#======================================================================
#===============================================================================
def error (msg):
#===============================================================================
print line
print "-" * charIndex, "^"
print("Error on %d - %s\n" % (number, msg))
printToken(token)
print("\n")
#===============================================================================
def emit (memadr, opcode, parameter):
#===============================================================================
"""EMIT CODE - Emit a of code with a Parameter
if first arg is zero - (the memory address), use and incr CODEPTR"""
global codeptr
if (memadr == 0):
memadr = codeptr
codeptr = codeptr + 1
print "%6d %-8s %-7s" % (memadr, opcode, parameter)
#===============================================================================
def declareList() :
# declareList ::= varDeclare {, varDeclare};
#===============================================================================
varDeclare()
while token.token != semicolon :
if token.token == comma:
varDeclare()
getoken()
#===============================================================================
def varDeclare() :
# <varDeclare> ::= idsym [ = number | "[" number "]"
#===============================================================================
ta = 0
tn = []
global varptr;
global whichidaddress;
global arraySubaddress;
getoken();
if token.token == idsym:
ta = token.address
tn = token.name
getoken()
if token.token == leftsquarebracket:
getoken()
if token.token == number: # number
symtbl[tn].address = varptr;
while (token.value != 0):
varptr = varptr + 1
token.value = token.value - 1
getoken()
if token.token == rightsquarebracket:
getoken()
else:
error("Expected rightsquarebracket at the end of arraySub declare")
else:
if ta != 0:
print("#"),
print("%c already declared\n", tn);
# assignStmt()
else:
symtbl[tn].address = varptr;
varptr = varptr + 1;
# emit(0, "load", varptr)
#===============================================================================
def variable():
# <variable> ::= <id> [<arraySub>]
#===============================================================================
if token.token == idsym:
expression()
# getoken()
if token.token == leftsquarebracket:
arraySub()
#===============================================================================
def arraySub():
# <arraySub> ::= "["<expression>"]"
#===============================================================================
global arraySub;
expression()
if token.token == rightsquarebracket:
getoken()
else:
error("Expected rightsquarebracket for array expression")
#===============================================================================
def parameters():
#===============================================================================
varDeclare()
if token.token == comma:
varDeclare()
# getoken()
#======================================================================
# STMTLIST
# <stmtlist> ::= <stmt> { ; <stmt> }
#===============================================================================
def stmtList():
#===============================================================================
stmt()
while (token.token != rightbrace):
stmt()
#======================================================================
# STMT
# <stmt> ::= variable( = expression | parameter) | <printStmt> ::= print "("<print_item>{,<print_item>}")"| if <condition> <stmt> [else <stmt>]|
# <readStmt> ::= read "("variable")" | <id> = <expression> |
# while <condition> <stmt>| <stmtList> | do <stmsList> forever | break | continue
#===============================================================================
def stmt():
#===============================================================================
global codeptr
thisStmtAdr = codeptr # Jump DEMO - not part of Stmt
if token.token == variable:
getoken()
if token.token == assignsym:
expression()
else:
parameter()
elif token.token == ifsym:
ifStmt()
elif token.token == whilesym:
whileStmt()
elif token.token == stmtList:
stmtList()
elif token.token == printsym:
printStmt()
elif token.token == readsym:
readStmt()
elif token.token == declaresym:
declareList()
elif token.token == dosym:
doStmt()
elif token.token == breaksym:
emit(0, "halt", '')
getoken()
elif token.token == continuesym:
continueStmt()
elif token.token == number:
expression()
elif token.token == idsym:
assignStmt()
elif token.token == functionsym:
function()
elif token.token == returnsym:
returnStmt()
else:
error("Expected start of a statement")
if token.token == semicolon or token.token == comma:
getoken()
#===============================================================================
def printStmt():
# <printStmt> ::= print "("<print_item>{,<print_item>}")"
#===============================================================================
getoken() # skip "print"
if token.token == leftbracket:
getoken()
else:
error("Expected leftbracket before the print-item")
print_item()
if token.token == comma:
print_item()
getoken()
if token.token == rightbracket:
getoken()
if token.token == semicolon:
getoken()
#===============================================================================
def print_item():
# <print_item> ::= expression | string
#===============================================================================
# expression
if token.token == idsym:
expression()
emit(0, "writeint", 0)
getoken()
# string
if token.token == stringsym:
printMsg()
getoken()
#===============================================================================
def printMsg():
# <printMsg> ::= printMsg <expression>
#===============================================================================
emit(0, "loadv", counterafter1)
emit(0, "store", 1)
emit(0, "call", 400)
emit(400, "load-Ind", 0)
emit(401, "jumpeq", 405)
emit(402, "writech", 0)
emit(403, "increment", 1)
emit(404, "jump", 400)
emit(405, "return", '')
#===============================================================================
def readStmt():
# <readStmt> ::= read "("variable")"
#===============================================================================
global idaddress
getoken()
if token.token == leftbracket:
getoken()
else:
error("Expected leftbracket before the variable")
variable()
emit(0, "readint", idaddress)
if token.token == rightbracket:
getoken()
else:
error("Expected rightbracket after the variable")
#===============================================================================
def assignStmt():
#===============================================================================
"""
<id> = <expression>
"""
global tokennum
global whichidentifier
global whichidaddress
global arraySubaddress
whichidentifier = token.name # Remember which ID on Left
tempadd = token.address
if arraySubaddress != 0:
whichidaddress = token.address;
else:
whichidaddress = arraySubaddress;
getoken() # Get token after identifier
if token.token == assignsym:
getoken()
else:
error("Expected = in assignment statement")
expression()
passtoken = token.value
emit(0, "store", tempadd)
getoken()
#===============================================================================
def ifStmt():
# <ifStmt> ::= if (condition) statement [else statement]
#===============================================================================
getoken() # skip "if"
if token.token == leftbracket:
getoken()
else:
error("Expected leftbracket at the start of if-condition")
condition()
if token.token == rightbracket:
getoken()
else:
error("Expected rightbracket at the end of if-condition")
if token.token == leftbrace:
getoken()
else:
error("Expected leftbrace at the start of if-statement")
stmtList()
getoken()
if token.token == rightbrace:
getoken()
if token.token == elsesym:
getoken()
if token.token == leftbrace:
getoken()
else:
error("Expected leftbrace at the start of else-statement")
stmt()
getoken()
if token.token == rightbrace:
getoken()
else:
error("Expected rightbrace at the end of else-statement")
#===============================================================================
def whileStmt():
# <whileStmt> ::= while (condition)statement
#===============================================================================
getoken() # skip "while"
if token.token == leftbracket:
getoken()
else:
error("Expected leftbracket at the start of while-condition")
condition()
if token.token == rightbracket:
getoken()
else:
error("Expected rightbracket at the end of while-condition")
if token.token == leftbrace:
getoken()
else:
error("Expected leftbrace at the start of while-statement")
stmtList()
# emit(0,"jump",127)
if token.token == rightbrace:
getoken()
else:
error("Expected rightbrace at the end of while-statement")
#===============================================================================
def doStmt():
# doStmt ::= <do> stmtList <forever>
#===============================================================================
getoken()
stmtList()
#===============================================================================
def returnStmt():
#===============================================================================
getoken()
if token.token == leftbracket:
getoken()
if token.token == idsym:
expression()
emit(0, "jump", 0)
if token.token == rightbracket:
getoken()
else:
error("Expected rightbracket for return-statement")
#===============================================================================
def condition():
# condition ::= [not] conditional-expression
#===============================================================================
notsign = False;
if token.token == notsym:
notsign = True;
getoken()
if notsign == True:
emit(0, "Not", '')
conditionalexp()
else:
conditionalexp()
#===============================================================================
def conditionalexp():
# <conditionalexp> ::= <expression>[relational_op <expression>]
#===============================================================================
expression()
relational_op()
#===============================================================================
def relational_op():
# <relational_op> ::= <|<=|==|!=|>|>=
#===============================================================================
if token.token == lessthan or token.token == greaterthan or token.token == lessthanequal or token.token == greaterthanequal or token.token == jumpne or token.token == jumpeq:
op = token # remember -
getoken() # skip past -
emit(0, "store", 686) # Save current expression result
expression()
if op.token == lessthan:
emit(0, "store", 5)
emit(0, "load", 686)
emit(0, "compare", 5)
emit(0, "jumplt", 137)
emit(0, "jump", 158)
elif op.token == greaterthan:
emit(0, "store", 5)
emit(0, "load", 686)
emit(0, "compare", 5)
emit(0, "jumpgt", 158)
emit(0, "jump", 137)
elif op.token == lessthanequal:
emit(0, "store", 5)
emit(0, "load", 686)
emit(0, "compare", 5)
emit(0, "jumplt", 145)
emit(0, "jumpeq", 145)
emit(0, "jump", 159)
elif op.token == greaterthanequal:
emit(0, "store", 5)
emit(0, "load", 686)
emit(0, "compare", 5)
emit(0, "jumpgt", 145)
emit(0, "jumpeq", 145)
emit(0, "jump", 159)
elif op.token == jumpne:
emit(0, "store", 5)
emit(0, "load", 686)
emit(0, "compare", 5)
emit(0, "jumpne", 128)
emit(0, "jump", 125)
elif op.token == jumpeq:
emit(0, "store", 5)
emit(0, "load", 686)
emit(0, "compare", 5)
emit(0, "jumpeq", 125)
emit(0, "jump", 128)
#===============================================================================
def expression():
# <expression> ::= <term> { (+ | -) <term> }
#===============================================================================
"""
Leaves result in ACC at runtime
Use addresses 687 as Temporary variables
"""
global whichidentifier
global idaddress
global idvalue
if whichidentifier == None:
getoken()
else:
idaddress = symtbl[whichidentifier].address
idvalue = symtbl[whichidentifier].value
if token.token == leftbracket:
getoken()
term()
while token.token == plus or token.token == minus:
op = token # remember -
getoken() # skip past -
emit(0, "store", 687) # Save current result
term()
if op.token == plus:
emit(0, "add", 687)
elif op.token == minus: # Subtract - have to swap operand order
emit(0, "store", 5)
emit(0, "load", 687)
emit(0, "subtract", 5)
#===============================================================================
def term():
# <term> ::= <factor> {(*|/) <factor>}
#===============================================================================
"""
Use addresses 688 as Temporary variables
"""
factor()
while token.token == mpy or token.token == div:
op = token # remember -
getoken() # skip past -
emit(0, "store", 688) # Save term result
# save here xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
factor()
if op.token == mpy:
emit(0, "mpy", 688)
elif op.token == div:
emit(0, "store", 5)
emit(0, "load", 688)
emit(0, "div", 5)
#===============================================================================
def factor():
# <factor> ::= [+|-] <id> | <number> | "("<expression>")"
#===============================================================================
"""
# FACTOR() - leaves result in ACC at runtime
"""
global tokennum
global whichidentifier
global idaddress
global idvalue
tokensign = False
# [+|-] number
if token.token == plus:
getoken()
# - (unary)
elif token.token == minus:
tokensign = True
getoken()
# number
if token.token == number:
if tokensign == True:
emit(0, "loadv", 0 - token.value)
getoken()
else:
emit(0, "loadv", token.value)
tokennum = token.value
getoken()
# id
elif token.token == idsym:
emit(0, "load", token.address)
idaddress = token.address
tempaddress = token.address
getoken()
if token.token == leftbracket:
getoken()
expression()
if token.token == comma:
# For two parameters
emit(0, "store", tempaddress + 1)
getoken()
expression()
emit(0, "call", 419)
else:
# For one parameter
emit(0, "store", tempaddress + 2)
emit(0, "call", 410)
if token.token == rightbracket:
getoken()
else:
error("Expected rightbracket after the factor")
# "(" <expression> ")"
elif token.token == leftbracket:
emit(0, "store", 689)
emit(0, "push", 1)
getoken()
expression()
if token.token == rightbracket:
getoken()
emit(0, "pop", 1)
else:
error("Start Of Factor Expected")
#===============================================================================
def function():
#===============================================================================
global codeptr
global endaddress
beginaddress = codeptr
if endaddress < 200:
codeptr = codeptr + 400
elif endaddress > 400:
codeptr = endaddress
getoken()
if token.token == idsym:
getoken()
if token.token == leftbracket:
getoken()
if token.token == idsym:
parameters()
else:
error("Function error : No_parameter_input_for_function")
if token.token == rightbracket:
getoken()
else:
error("Expected rightbracket for parameter")
if token.token == semicolon:
getoken()
else:
error("Expected semicolon after parameter")
if token.token == declaresym:
declareList()
if token.token == leftbrace:
getoken()
stmtList()
if token.token == rightbrace:
getoken()
print ("#---Function Finished---")
endaddress = codeptr
#===============================================================================
def program():
# <program> ::= program <id>; declare declareList; { StmtList}
#===============================================================================
global codeptr
beginaddress = codeptr
if token.token == leftbrace:
getoken()
if token.token == programsym:
getoken()
else: error("Program start with 'program' keyword")
if token.token == idsym:
getoken()
if token.token == semicolon:
getoken()
if token.token == declaresym :
declareList()
while token.token == functionsym:
function()
codeptr = beginaddress
if token.token == leftbrace:
getoken()
stmtList()
if token.token == rightbrace:
print "#***Compilation Finished****"
#======================================================================
def main():
#======================================================================
global line
global srcfile
global charIndex
initSymTbl()
with open("test2.txt") as srcfile:
line = srcfile.read()
charIndex = 0
debugScanner = False
if debugScanner: # Scanner Test Routine - Read a line and display the tokens
getoken()
while token.token is not None: # Skeleton for testing Scanner
printToken(token)
getoken()
sys.exit(1)
else:
getoken() # Parse Program according to the grammar
program()
#===============================================================================
# Main Compiler starts here
#===============================================================================
print "#Microcompiler.py"
main()
"""
srcfile = open('test.txt', 'r')
lexer = shlex.shlex(srcfile)
for token in lexer:
print repr(token)
"""
| [
[
1,
0,
0.0008,
0.0008,
0,
0.66,
0,
540,
0,
1,
0,
0,
540,
0,
0
],
[
14,
0,
0.0025,
0.0008,
0,
0.66,
0.0164,
777,
1,
0,
0,
0,
0,
3,
0
],
[
8,
0,
0.0169,
0.0228,
0,
0... | [
"import re",
"__author__ = 'YeeHin Kwok'",
"\"\"\" MicroCompiler \n\n<program> ::= program <id>; declare declareList; { StmtList}\n<declareList> ::= varDeclare {, varDeclare};\n<varDeclare> ::= idsym [ = number | \"[\" number \"]\" \n\n<stmt> ::= variable( = expression | parameter) ... |
import re
__author__ = 'YeeHin Kwok'
""" Giovanni's MicroCompiler Demo
<program> ::= { <id> ; <vars > <stmtlist> }
<vars> ::= V { <id> ; } % DECLARATIONS
<stmtlist> ::= <stmt> { ; <stmt> }
<stmt> ::= P <id> | <id> = <expr>
<expr> ::= <factor> { (+ | -) <factor> } % No precedence
<factor> ::= ID | Number
"""
import sys
import shlex
#===============================================================================
# # Lexical Analyser - the "Scanner" - Define the TokenTypes
#===============================================================================
tokenNames = \
[ "unknownToken", "idsym", "assignsym", "leftbrace", "rightbrace",
"varsym", "semicolon", "whilesym", "leftbracket", "rightbracket",
"printsym", "ifsym", "equals", "lessthan", "greaterthan",
"number", "plus", "minus", "mpy", "div", "elsesym", "declaresym", "forsym", "andsym", "elifsym", "dosym", "returnsym",
"continuesym", "breaksym", "nonesym", "programsym", "functionsym", "leftsquarebrace", "rightsquarebrace",
"lessthanequal", "colon", "comma", "comment", "commentstr", "dot", " greaterthanequal", "jumpeq", "jumpne",
"andop", "orop", "quote ", "stringsym", "arraysym", "readsym", "endfile"]
# define the tokens as variables
unknownToken, idsym, assignsym, leftbrace, rightbrace, \
varsym, semicolon, whilesym, leftbracket, rightbracket, \
printsym, ifsym, equals, lessthan, greaterthan, \
number, plus, minus, mpy, div, elsesym, declaresym, forsym, andsym, elifsym, dosym, returnsym, \
continuesym, breaksym, nonesym, programsym, functionsym, leftsquarebrace, rightsquarebrace, \
lessthanequal, colon, comma, comment, commentstr, dot, greaterthanequal, jumpeq, jumpne, \
andop, orop, quote, stringsym, arraysym, readsym, endfile = range(0, len(tokenNames))
#===============================================================================
class symbol:
#===============================================================================
name = None # String representation
token = None; # Corresponding token
address = 0; # For variables, their runtime address
value = None # on defined for numbers
def __init__(self, name, token, value=0):
self.name = name
self.token = token
self.address = 0 # for identifiers, their address
self.value = value # for numbers, their value
symtbl = {}; # The Symbol Table, a dictionary of symbols indexed by name
#======================================================================
# GLOBALS for output of Lexical Analyser
# Set by each call to GeToken()
token = None; # A symbol
line = "\n" # the complex source file as a string
charIndex = 0 # the position in the source
linenumber = 0 # The current number
i = 100
j = 100
counterafter = i
counterafter1 = j
EOF = chr(0)
#======================================================================
# Run Time Code Generation Variables
varptr = 500 # Arbitrary base address of memory for variables
codeptr = 10 # Address to output next instruction (for code)
#===============================================================================
# Symbol Table Management Routines
#===============================================================================
#===============================================================================
def addToSymTbl (name, token):
#===============================================================================
symtbl[name] = symbol(name, token) # Add a new symbol to the dictionary
return symtbl[name]
#===============================================================================
def lookup (thisName):
#===============================================================================
"# Find a given identifier in the Symbol Table, Return the symtbl entry"
if symtbl.has_key(thisName): # thisName has been seen before
return symtbl[thisName] # return the symtbl entry
else: return None
#===============================================================================
def initSymTbl():
#===============================================================================
"# Initialise Symbol Table, and preload reserved words"
addToSymTbl('var', varsym) # VAR
addToSymTbl('program', programsym)
addToSymTbl('function', functionsym)
addToSymTbl('while', whilesym) # WHILE
addToSymTbl('print', printsym) # PRINT
addToSymTbl('else', elsesym)
addToSymTbl('elif', elifsym)
addToSymTbl('if', ifsym)
addToSymTbl('declare', declaresym)
addToSymTbl('for', forsym)
addToSymTbl('None', nonesym)
addToSymTbl('continue', continuesym)
addToSymTbl('read', readsym) # READINT
addToSymTbl('do', dosym)
addToSymTbl('return', returnsym)
# Now add symbols - NB only single character symbols are here
# multicharacter one like ">=" are still to do
addToSymTbl('=', assignsym)
addToSymTbl('#', comment)
addToSymTbl('<', lessthan)
addToSymTbl('>', greaterthan)
addToSymTbl('{', leftbrace)
addToSymTbl('}', rightbrace)
addToSymTbl('(', leftbracket)
addToSymTbl(')', rightbracket)
addToSymTbl('+', plus)
addToSymTbl('-', minus)
addToSymTbl(';', semicolon)
addToSymTbl('break', breaksym)
addToSymTbl('*', mpy)
addToSymTbl('/', div)
addToSymTbl('[', leftsquarebrace)
addToSymTbl(']', rightsquarebrace)
addToSymTbl(':', colon)
addToSymTbl(',', comma)
addToSymTbl('.', dot)
addToSymTbl('==', jumpeq)
addToSymTbl('!=', jumpne)
addToSymTbl('&&', andop)
addToSymTbl('||', orop)
addToSymTbl('"', quote)
addToSymTbl(EOF, endfile)
#===============================================================================
# Scanner Diagnostics
#===============================================================================
def printToken(tok):
#===============================================================================
" - display the specified token."
if tok.token == idsym:
print "Token = %10s, %-10s adr = %3d" % \
(tokenNames[tok.token], tok.name, tok.address)
elif tok.token == number:
print "Token = %10s %d" % (tokenNames[tok.token], tok.value)
else:
print "Token = %10s" % tokenNames[tok.token]
#==============================?=================================================
def dumpSymTbl():
#===============================================================================
""" Dump all the tokens in the symboltable """
print(" *** Symbol Table ***")
for name in symtbl.keys(): # keys is a list of the names (printable form of tokens)
tok = symtbl[name]
if tok.token == idsym:
printToken(tok)
#===============================================================================
def getch():
#===============================================================================
global line
global charIndex
global linenumber
while True:
if charIndex < len(line): # See if used up current line
ch = line[charIndex] # if not, get character
charIndex = charIndex + 1 # & move pointer for next time
else:
# line = f.readline()
# if line == "": line = EOF
print "#End of File"
print "#--> ",
line = raw_input() + "\n" # read new line, adding \n so it's like f.readline()
# line = srcfile.read()
charIndex = 0 # & reset character pointer
linenumber = linenumber + 1
continue
if ch == "\n":
ch = " "
if ch == '?':
dumpSymTbl()
continue
return ch
#===============================================================================
def ungetch():
#===============================================================================
""" Unget the next character peeked at when building variables, numbers
and when distinguishing between >= and > ...
"""
global charIndex;
charIndex = charIndex - 1;
#===============================================================================
def getoken():
#===============================================================================
""" GETOKEN - Put next token into the global TOKEN """
global token
global i
global m
global counterafter
global counterafter1
x = 0
ch = getch() # skip whitespace
while ch in ["\t", " ", "\n"]:
ch = getch()
# If ch is alphabetic then this is start of reserved word or an identifier
if ch.isalpha(): # Letter therefore it's either identifier or reserved word
name = ""
while ch.isalpha() or ch.isdigit() or ch == "_":
name = name + ch
ch = getch()
ungetch() # let terminator be used next time
token = lookup(name) # See if token's known
if token is None: # if not
token = addToSymTbl(name, idsym) # add as 'idsym'-IDENTIFIER
return # we've set token.token to either id or tokentype of reserved word
elif ch in ["{", "}", "(", ")", "[", "]", "+", "-", "*", "/", ";", ",", ":", EOF]:
token = lookup(ch) # preloaded with appropriate token
elif ch.isdigit():
# In the real version, build number and don't forget to end with ungetch()
while(ch.isdigit() == True):
x = str(x) + str(ch)
ch = getch()
ch = ungetch()
token = symbol(x, number, value=int(x)) # simplistic SINGLE DIGIT Ascii to Binary
return
# elif ch == "-":
# x = ""
# no =""
# ch = getch()
# if ch.isdigit() ==True:
# while ch.isdigit():
# x = str(x) + str(ch)
# ch = getch()
#
# ch = ungetch()
#
# no = "-" + str(x)
#
# token = symbol(no, number, value = int(no))
elif ch == '#':
str1 = ""
ch = getch()
while(ch != " "):
str1 = str(str1) + str(ch)
ch = getch()
ch = getch()
token = symbol(str1, commentstr, value=str(str1)) # simplistic SINGLE DIGIT Ascii to Binary
print("#comment: " + str(str1))
return
elif ch == '"':
a = ""
ch = getch()
counterafter1 =counterafter
i=counterafter
if counterafter != 100:
counterafter=counterafter+4;
counterafter = i
while (ch != '"'):
a = str(a) + str(ch)
if ch != " ":
b = "'"+ch+"'"
emit(i, "constant",b)
ch = getch()
i=i+1
emit(i, "constant", 13)
emit(i+1, "constant", 0)
# emit(i+2, "writech", '')
emit(i+2, "return", '')
ch = getch()
counterafter=i+3
token = symbol(a, stringsym, value=str(a)) # simplistic SINGLE DIGIT Ascii to Binary
# printMsg()
return
elif ch == "<":
ch = getch()
if ch == "=":
lt = ""
lt = "<" + "="
token = symbol(lt, lessthanequal, value=str(lt)) # simplistic SINGLE DIGIT Ascii to Binary
return
else:
ch == ungetch()
token = symbol("<", lessthan, value="<") # simplistic SINGLE DIGIT Ascii to Binary
return
elif ch == "!":
ne = ""
ch = getch()
if ch == "=":
ne = "!" + "="
token = symbol(ne, jumpne, value=str(ne)) # simplistic SINGLE DIGIT Ascii to Binary
return
else:
ch == ungetch()
token = symbol("!", NOT , value="!") # simplistic SINGLE DIGIT Ascii to Binary
return
elif ch == "=":
eq = ""
ch = getch()
if ch == "=":
eq = "=" + "="
token = symbol(eq, jumpeq, value=str(eq)) # simplistic SINGLE DIGIT Ascii to Binary
return
else:
ch == ungetch()
token = symbol("=", assignsym, value="=") # simplistic SINGLE DIGIT Ascii to Binary
return
elif ch == ">":
gt = ""
ch = getch()
if ch == "=":
gt = ">" + "="
token = symbol(gt, lessthanequal, value=str(gt)) # simplistic SINGLE DIGIT Ascii to Binary
return
else:
ch == ungetch()
token = symbol(">", greaterthan, value=">") # simplistic SINGLE DIGIT Ascii to Binary
return
else:
print "Unknown character -->%s<- decimal %d" % (ch, ord(ch))
sys.exit(1) # Abort Compilation
#======================================================================
# THE GRAMMAR
# <program> ::= { <id> ; <vars > <stmtlist> }
# <vars> ::= var { <id> ; } % DECLARATIONS
# <array> ::= [<expr>]
# <stmtlist> ::= <stmt> { ; <stmt> }
# <stmt> ::= print <id>
# <id> = <expr>
# <expr> ::= <factor> { (+ | - | * | /) <factor> } % No precedence
# <factor> ::= [+/-] ID | Number
#======================================================================
# Centralised Parser Error Message handler
#======================================================================
#===============================================================================
def error (msg):
#===============================================================================
print line
print "-" * charIndex, "^"
print("Error on %d - %s\n" % (number, msg))
printToken(token)
print("\n")
#===============================================================================
def emit (memadr, opcode, parameter):
#===============================================================================
"""EMIT CODE - Emit a of code with a Parameter
if first arg is zero - (the memory address), use and incr CODEPTR"""
global codeptr
if (memadr == 0):
memadr = codeptr
codeptr = codeptr + 1
print "%6d %-8s %-7s" % (memadr, opcode, parameter)
#======================================================================
# VARIABLE DECLARATIONS
# <vars> ::= V { <id> ; }
#===============================================================================
def vars() :
#===============================================================================
ta = 0
tn = []
global varptr;
getoken();
if token.token == idsym:
ta = token.address
tn = token.name
getoken()
if token.token == leftsquarebrace:
getoken()
if token.token == number:
# emit(0, "loadv",token.value)
# emit(0, "store", token.value+300)
array()
if token.token == rightsquarebrace:
getoken()
else:
error("var error: ] expected - 1")
else:
getoken()
elif tn == "i":
# print("#The array name is " + str(tn)+"\n")
if token.token == rightsquarebrace:
getoken()
else:
if ta != 0:
print("%c already declared\n", tn);
#assignStmt()
else:
symtbl[tn].address = varptr;
varptr = varptr + 1
# emit(0, "load", varptr)
if token.token == assignsym:
getoken()
expression()
if token.token == rightbracket:
getoken()
if token.token == comma:
vars()
elif token.token == semicolon : getoken()
else: error("comma or semicolon expected in declaration")
#===============================================================================
def array():
#===============================================================================
global array;
# getoken()
while (token.token == number):
print("#array address")
emit(0, "store", token.value + 400)
print("#array value " +str(token.value))
getoken();
#======================================================================
# STMTLIST
# <stmtlist> ::= <stmt> { ; <stmt> }
#===============================================================================
def stmtList():
#===============================================================================
stmt()
while (token.token != rightbrace):
stmt()
#======================================================================
# STMT
#===============================================================================
def stmt():
#===============================================================================
""" <stmt> ::= print <expression|string>| read <vars> | <id> = <expression> |
if <condition> <stmt> [else <stmt>]| while <condition> <stmt>|
<stmtList> | do <stmsList> forever | break | continue
"""
global codeptr
thisStmtAdr = codeptr # Jump DEMO - not part of Stmt
# if token.token == arraysym:
# array()
if token.token == printsym:
printStmt()
elif token.token == readsym:
readStmt()
elif token.token == number:
expression()
elif token.token == idsym:
assignStmt()
elif token.token == ifsym:
ifStmt()
elif token.token == elsesym:
elseStmt()
elif token.token == whilesym:
whileStmt()
elif token.token == dosym:
doStmt()
elif token.token == returnsym:
returnStmt()
elif token.token == functionsym:
function()
elif token.token == continuesym:
continueStmt()
elif token.token == leftbracket:
getoken()
elif token.token == leftbrace:
getoken()
elif token.token == stringsym:
# print(str(token.name))
printMsg()
getoken()
elif token.token == assignsym:
getoken()
elif token.token == commentstr:
# print(str(token.name))
getoken()
elif token.token == breaksym:
getoken()
elif token.token == lessthanequal:
getoken()
elif token.token == greaterthanequal:
getoken()
elif token.token == jumpeq:
getoken()
elif token.token == jumpne:
getoken()
elif token.token == rightbracket:
getoken()
elif token.token == semicolon:
getoken()
elif token.token == comma:
getoken()
elif token.token == rightsquarebrace:
getoken()
elif token.token == rightbrace:
getoken()
else:
error("Expected start of a statement")
# emit (0, "return", thisStmtAdr) Jump DEMO need in break program
#===============================================================================
def printStmt():
#===============================================================================
""" <printStmt> ::= print <expression|string>"""
getoken()# skip "print"
if token.token == idsym:
if token.token == leftbracket:
returnStmt
else:
stmt()
emit(0, "load", 501)
expression()
emit(0, "writeint", 502)
emit(0, "writeint", 7)
emit(0, "writeint", 501)
#===============================================================================
def printMsg():
#===============================================================================
""" <printMsg> ::= printMsg <expression>"""
# print("#"+str(counterafter)+ " counterafter")
# print("#"+str(counterafter1)+ " counterafter1")
# if counterafter != 100:
# emit(0,"loadv",counterafter )
emit(0, "loadv", counterafter1)
emit(0, "store", 1)
emit(0, "call", 400)
emit(400, "load-Ind", 0)
emit(401, "jumpeq", 405)
emit(402, "writech",0)
emit(403, "increment", 1)
emit(404, "jump", 400)
emit(405, "return", '')
#===============================================================================
def readStmt():
#===============================================================================
""" <readStmt> ::= read <vars>"""
getoken()
emit(0, "readint", 7)
emit(0, "store", 502)
getoken()
#===============================================================================
def assignStmt():
#===============================================================================
"""
<id> = <expression>
"""
whichidentifier = token # Remember which ID on Left
getoken() # Get token after identifier
if token.token == assignsym:
getoken()
elif token.token == leftsquarebrace:
vars()
elif token.token == leftbrace:
vars()
elif token.token == jumpeq:
getoken()
elif token.token == jumpne:
getoken()
elif token.token == rightbracket:
getoken()
elif token.token == lessthanequal:
getoken()
elif token.token == idsym:
getoken()
elif token.token == leftbracket:
getoken()
elif token.token == comma:
getoken()
elif token.token == greaterthanequal:
getoken()
# elif token.token == idsym: factor()
else:
error("Expected = in assignment statement")
expression()
# Save result into LHS runtime address
#===============================================================================
def ifStmt():
# if-then-else
#===============================================================================
""" <ifStmt> ::= if <expression>"""
print("#IFSmt")
getoken() # skip "if"
expression()
stmt()
expression()
#===============================================================================
def elseStmt():
# if-then-else
#===============================================================================
""" <elseStmt> ::= else <expression>"""
print("#ElseSmt")
emit(200, "jump", 47) # less than 2 go to else
getoken()
stmt()
expression()
# emit(314, "jump", 22)
#===============================================================================
def whileStmt():
#===============================================================================
""" <whileStmt> ::= while (condition)statement"""
# emit(0, "load", 201)
emit(0, "store", 502)
getoken()
expression() # num>0
# emit(0, "jump", 22)
stmt()
#===============================================================================
def returnStmt():
#===============================================================================
emit(600,"add", 201)
emit(601,"store", 502)
emit(602,"return", '')
getoken()
#===============================================================================
def expression():
#===============================================================================
"""
Leaves result in ACC at runtime
Use addresses 999 & 998 as Temporary variables
<expression> ::= <factor> { (+ | -) <factor> }
"""
if token.token == leftbracket: getoken()
factor()
## 1st start==============================================================================
while token.token == plus or token.token == minus or token.token == mpy or token.token == div or token.token == lessthan or token.token == greaterthan or token.token == lessthanequal or token.token == greaterthanequal or token.token == jumpne or token.token == jumpeq:
op = token # remember -
getoken() # skip past -
# emit(0, "store", 997) # Save current result
factor()
if op.token == plus:
emit(0, "add", 502)
emit(0, "store", 502)
# emit(0, "jump", 22)
# if op.token == leftbracket:getoken()
if op.token == minus:
## 2nd start==============================================================================
if token.token == plus or token.token == minus or token.token == mpy or token.token == div:
op2 = token# remember *
getoken() # skip past *
factor()
if op2.token == plus: # Subtract - have to swap operand order
emit(0, "load", 210)
emit(0, "add", 203)
emit(0, "store", 500)
if op2.token == minus: # Subtract - have to swap operand order
emit(0, "load", 501)
emit(0, "subtract", 201)
emit(0, "store", 501)
if op2.token == mpy:
## 3rd start==============================================================================
while token.token == plus or token.token == minus or token.token == mpy or token.token == div:
op3 = token# remember *
getoken() # skip past *
factor()
if op3.token == plus: # Subtract - have to swap operand order
emit(0, "load", 210)
emit(0, "add", 203)
emit(0, "store", 500)
if op3.token == minus: # Subtract - have to swap operand order
emit(0, "load", 501)
emit(0, "subtract", 210)
emit(0, "store", 501)
if op3.token == mpy:
factor()
## 4th start==============================================================================
while token.token == plus or token.token == minus or token.token == mpy or token.token == div:
if token.token == plus:
op4 = token# remember +
getoken() # skip past +
factor()
if op4.token == plus: # Subtract - have to swap operand order
emit(0, "load", 210)
emit(0, "add", 203)
emit(0, "store", 500)
if token.token == minus:
op4 = token# remember -
getoken() # skip past -
factor()
if op4.token == minus: # Subtract - have to swap operand order
emit(0, "load", 210)
emit(0, "subtract", 203)
emit(0, "store", 500)
if token.token == mpy:
op4 = token
getoken()
factor()
if op4.token == mpy: # Subtract - have to swap operand order
emit(0, "load", 210)
emit(0, "mpy", 203)
emit(0, "store", 500)
if token.token == div:
op4 = token
getoken()
factor()
if op4.token == div: # Subtract - have to swap operand order
emit(0, "load", 210)
emit(0, "div", 203)
emit(0, "store", 500)
## 4th end==============================================================================
emit(0, "mpy", 205)
emit(0, "store", 501)
## 3rd end==============================================================================
emit(0, "mpy", 210)
emit(0, "store", 501)
## 2nd end==============================================================================
emit(0, "load", 590)
emit(0, "subtract", 501)
emit(0, "store", 501)
# emit(0, "jump", 24)
elif op.token == mpy:
emit(0, "load", 206)
emit(0, "mpy", 7)
emit(0, "store", 502)
elif op.token == minus: # Subtract - have to swap operand order
emit(0, "load", 590)
emit(0, "subtract", 201)
emit(0, "store", 501)
emit(0, "writeInt", 502)
elif op.token == div:
emit(0, "load", 502)
emit(0, "div", 202)
emit(0, "store", 7)
elif op.token == lessthan:
emit(0, "load", 501)
emit(0, "compare", 212)
emit(0, "jumplt", 300)
emit(300, "writeInt", 502)
elif op.token == greaterthan:
emit(0, "load", 208)
emit(0, "compare", 7)
emit(0, "jumpgt", 47)
elif op.token == lessthanequal:
emit(0, "load", 501)
emit(0, "compare", 212)
emit(0, "jumplt", 300)
emit(300, "writeInt", 502)
elif op.token == greaterthanequal:
emit(0, "load", 501)
emit(0, "compare", 212)
emit(0, "jumpgt", 300)
emit(300, "writeInt", 502)
elif op.token == jumpne:
emit(0, "load", 205)
emit(0, "compare", 502)
emit(0, "jumpne", 310)
emit(0, "writeInt", 0)
emit(0, "halt", 0)
emit(310, "writeInt", 502)
elif op.token == jumpeq:
emit(0, "load", 210)
emit(0, "compare", 7)
emit(0, "jumpgt", 29)
#===============================================================================
def factor():
#===============================================================================
"""
# FACTOR() - leaves result in ACC at runtime
<factor> ::= identifier | number
"""
if token.token == plus:
getoken()
# - (unary)
elif token.token == minus:
getoken()
if token.token == idsym:
emit(0, "load", token.address)
getoken()
elif token.token == stringsym: #################
print("#String: " + str(token.name))
printMsg()
getoken()
elif token.token == number:
if token.value == 5:
emit(0, "loadv", token.value)
emit(0, "store", 200 + token.value)
emit(0, "call", 600)
emit(0, "writeint", 502)
getoken()
else:
emit(0, "loadv", token.value)
emit(0, "store", 200 + token.value)
getoken()
elif token.token == commentstr:
# print ("#Comment: " + str(token.name))
getoken()
# elif token.token == assignsym:
# getoken()
elif token.token == leftbracket:
getoken()
# print "this is token",tokenNames[token.token]
elif token.token == leftsquarebrace: getoken()
elif token.token == rightbracket:
getoken()
elif token.token == breaksym:
emit(0,"halt", 0)
elif token.token == lessthanequal:
getoken()
elif token.token == greaterthanequal:
getoken()
elif token.token == jumpeq:
getoken()
elif token.token == rightsquarebrace:
getoken()
elif token.token == semicolon:
getoken()
elif token.token == comma:
getoken()
elif token.token == leftbrace:
getoken()
elif token.token == functionsym:
getoken()
elif token.token == rightbrace:
print("")
elif token.token == ifsym:
ifStmt()
elif token.token == printsym:
getoken()
elif token.token == returnsym:
getoken()
else:
error("Start Of Factor Expected")
#===============================================================================
def function():
#===============================================================================
if token.token == functionsym:
getoken()
if token.token == idsym:
getoken()
if token.token == idsym:
getoken()
if token.token == varsym :
vars()
if token.token == declaresym :
vars()
if token.token == varsym :
vars()
if token.token == leftbrace:
vars()
stmtList()
if token.token == rightbrace:
print ("#---Function Finished---")
#===============================================================================
def program():
#===============================================================================
if token.token == leftbrace:
getoken()
if token.token == programsym:
getoken()
# else: error("Program start with 'program' keyword")
if token.token == idsym:
getoken()
# else: error("Program name expected")
if token.token == semicolon:
getoken()
# else: error("Semicolon expected")
if token.token == declaresym :
vars()
if token.token == varsym :
vars()
if token.token == functionsym:
function()
if token.token == leftbrace:
getoken()
stmtList()
stmtList()
if token.token == rightbrace:
print "#***Compilation Finished****"
#======================================================================
def main():
#======================================================================
global line
global srcfile
global charIndex
initSymTbl()
with open("test.txt") as srcfile:
# out1file = open('output.obj','w')
line = srcfile.read()
# out1file.write("hello")
# print line
charIndex = 0
debugScanner = False
if debugScanner: # Scanner Test Routine - Read a line and display the tokens
getoken()
while token.token is not None: # Skeleton for testing Scanner
printToken(token)
# y = str(token)
# out1file.write(y)
getoken()
sys.exit(1)
else:
getoken() # Parse Program according to the grammar
program()
#===============================================================================
# Main Compiler starts here
#===============================================================================
print "#Microcompiler.py v0.2"
emit(0, "load", 9)
main()
# emit(0, "constant", "'A'") #need in break,comment,exitloop,writer-if-read-write-ch program
# emit(0, "constant", 10)
# emit(0, "constant", 12)
# emit(0, "constant", 25)
# emit(0, "constant", -10)
"""
srcfile = open('tiny_1.txt', 'r')
lexer = shlex.shlex(srcfile)
for token in lexer:
print repr(token)
"""
# getoken()
#=======================================================================
# *** That's it folks - written by Giovanni Moretti - April 27, 2011 ***
#=======================================================================
| [
[
1,
0,
0.0009,
0.0009,
0,
0.66,
0,
540,
0,
1,
0,
0,
540,
0,
0
],
[
14,
0,
0.0026,
0.0009,
0,
0.66,
0.02,
777,
1,
0,
0,
0,
0,
3,
0
],
[
8,
0,
0.011,
0.0106,
0,
0.66... | [
"import re",
"__author__ = 'YeeHin Kwok'",
"\"\"\" Giovanni's MicroCompiler Demo\n\n<program> ::= { <id> ; <vars > <stmtlist> }\n<vars> ::= V { <id> ; } % DECLARATIONS\n\n<stmtlist> ::= <stmt> { ; <stmt> }\n<stmt> ::= P <id> | <id> = <expr>",... |
import re
__author__ = 'YeeHin Kwok'
""" Giovanni's MicroCompiler Demo
<program> ::= { <id> ; <varDeclare > <stmtlist> }
<varDeclare> ::= V { <id> ; } % DECLARATIONS
<stmtlist> ::= <stmt> { ; <stmt> }
<stmt> ::= P <id> | <id> = <expr>
<expr> ::= <factor> { (+ | -) <factor> } % No precedence
<factor> ::= ID | Number
"""
import sys
import shlex
#===============================================================================
# # Lexical Analyser - the "Scanner" - Define the TokenTypes
#===============================================================================
tokenNames = \
[ "unknownToken", "idsym", "assignsym", "leftbrace", "rightbrace",
"varDeclareym", "semicolon", "whilesym", "leftbracket", "rightbracket",
"printsym", "ifsym", "equals", "lessthan", "greaterthan",
"number", "plus", "minus", "mpy", "div", "elsesym", "declaresym", "forsym", "andsym", "elifsym", "dosym", "returnsym", "notsym",
"continuesym", "breaksym", "nonesym", "programsym", "functionsym", "leftsquarebracket", "rightsquarebracket",
"lessthanequal", "colon", "comma", "comment", "commentstr", "dot", " greaterthanequal", "jumpeq", "jumpne",
"andop", "orop", "quote ", "stringsym", "arraySubsym", "readsym", "endfile"]
# define the tokens as variables
unknownToken, idsym, assignsym, leftbrace, rightbrace, \
varDeclareym, semicolon, whilesym, leftbracket, rightbracket, \
printsym, ifsym, equals, lessthan, greaterthan, \
number, plus, minus, mpy, div, elsesym, declaresym, forsym, andsym, elifsym, dosym, returnsym, notsym, \
continuesym, breaksym, nonesym, programsym, functionsym, leftsquarebracket, rightsquarebracket, \
lessthanequal, colon, comma, comment, commentstr, dot, greaterthanequal, jumpeq, jumpne, \
andop, orop, quote, stringsym, arraySubsym, readsym, endfile = range(0, len(tokenNames))
#===============================================================================
class symbol:
#===============================================================================
name = None # String representation
token = None; # Corresponding token
address = 0; # For variables, their runtime address
value = None # on defined for numbers
def __init__(self, name, token, value=0):
self.name = name
self.token = token
self.address = 0 # for identifiers, their address
self.value = value # for numbers, their value
symtbl = {}; # The Symbol Table, a dictionary of symbols indexed by name
#======================================================================
# GLOBALS for output of Lexical Analyser
# Set by each call to GeToken()
token = None; # A symbol
line = "\n" # the complex source file as a string
charIndex = 0 # the position in the source
linenumber = 0 # The current number
tokennum = 0
resultnum = 0
whichidentifier = None;
identifieraddress = 0;
arraySubaddress = 0;
arrstar = 0;
returnadd = 0;
endaddress = 0;
i = 700
j = 700
counterafter = i
counterafter1 = j
EOF = chr(0)
#======================================================================
# Run Time Code Generation Variables
varptr = 500 # Arbitrary base address of memory for variables
codeptr = 10 # Address to output next instruction (for code)
#===============================================================================
# Symbol Table Management Routines
#===============================================================================
#===============================================================================
def addToSymTbl (name, token):
#===============================================================================
symtbl[name] = symbol(name, token) # Add a new symbol to the dictionary
return symtbl[name]
#===============================================================================
def lookup (thisName):
#===============================================================================
"# Find a given identifier in the Symbol Table, Return the symtbl entry"
if symtbl.has_key(thisName): # thisName has been seen before
return symtbl[thisName] # return the symtbl entry
else: return None
#===============================================================================
def initSymTbl():
#===============================================================================
"# Initialise Symbol Table, and preload reserved words"
addToSymTbl('var', varDeclareym) # VAR
addToSymTbl('program', programsym)
addToSymTbl('function', functionsym)
addToSymTbl('while', whilesym) # WHILE
addToSymTbl('print', printsym) # PRINT
addToSymTbl('else', elsesym)
addToSymTbl('elif', elifsym)
addToSymTbl('if', ifsym)
addToSymTbl('declare', declaresym)
addToSymTbl('for', forsym)
addToSymTbl('None', nonesym)
addToSymTbl('continue', continuesym)
addToSymTbl('read', readsym) # READINT
addToSymTbl('do', dosym)
addToSymTbl('return', returnsym)
addToSymTbl('not', notsym)
# Now add symbols - NB only single character symbols are here
# multicharacter one like ">=" are still to do
addToSymTbl('=', assignsym)
addToSymTbl('#', comment)
addToSymTbl('<', lessthan)
addToSymTbl('>', greaterthan)
addToSymTbl('{', leftbrace)
addToSymTbl('}', rightbrace)
addToSymTbl('(', leftbracket)
addToSymTbl(')', rightbracket)
addToSymTbl('+', plus)
addToSymTbl('-', minus)
addToSymTbl(';', semicolon)
addToSymTbl('break', breaksym)
addToSymTbl('*', mpy)
addToSymTbl('/', div)
addToSymTbl('[', leftsquarebracket)
addToSymTbl(']', rightsquarebracket)
addToSymTbl(':', colon)
addToSymTbl(',', comma)
addToSymTbl('.', dot)
addToSymTbl('==', jumpeq)
addToSymTbl('!=', jumpne)
addToSymTbl('&&', andop)
addToSymTbl('||', orop)
addToSymTbl('"', quote)
addToSymTbl(EOF, endfile)
#===============================================================================
# Scanner Diagnostics
#===============================================================================
def printToken(tok):
#===============================================================================
" - display the specified token."
if tok.token == idsym:
print "Token = %10s, %-10s adr = %3d, val = %d" % \
(tokenNames[tok.token], tok.name, tok.address, tok.value)
elif tok.token == number:
print "Token = %10s %d" % (tokenNames[tok.token], tok.value)
else:
print "Token = %10s" % tokenNames[tok.token]
#==============================?=================================================
def dumpSymTbl():
#===============================================================================
""" Dump all the tokens in the symboltable """
print("# *** Symbol Table ***")
for name in symtbl.keys(): # keys is a list of the names (printable form of tokens)
tok = symtbl[name]
if tok.token == idsym:
print("#"),
printToken(tok)
#===============================================================================
def getch():
#===============================================================================
global line
global charIndex
global linenumber
while True:
if charIndex < len(line): # See if used up current line
ch = line[charIndex] # if not, get character
charIndex = charIndex + 1 # & move pointer for next time
else:
# line = f.readline()
# if line == "": line = EOF
dumpSymTbl()
print "#End of File"
print "#--> ",
line = raw_input() + "\n" # read new line, adding \n so it's like f.readline()
# line = srcfile.read()
charIndex = 0 # & reset character pointer
linenumber = linenumber + 1
continue
if ch == "\n":
ch = " "
if ch == '?':
dumpSymTbl()
continue
return ch
#===============================================================================
def ungetch():
#===============================================================================
""" Unget the next character peeked at when building variables, numbers
and when distinguishing between >= and > ...
"""
global charIndex;
charIndex = charIndex - 1;
#===============================================================================
def getoken():
#===============================================================================
""" GETOKEN - Put next token into the global TOKEN """
global token
global i
global m
global counterafter
global counterafter1
x = 0
ch = getch() # skip whitespace
while ch in ["\t", " ", "\n"]:
ch = getch()
# If ch is alphabetic then this is start of reserved word or an identifier
if ch.isalpha(): # Letter therefore it's either identifier or reserved word
name = ""
while ch.isalpha() or ch.isdigit() or ch == "_":
name = name + ch
ch = getch()
ungetch() # let terminator be used next time
token = lookup(name) # See if token's known
if token is None: # if not
token = addToSymTbl(name, idsym) # add as 'idsym'-IDENTIFIER
return # we've set token.token to either id or tokentype of reserved word
elif ch in ["{", "}", "(", ")", "[", "]", "+", "-", "*", "/", ";", ",", ":", EOF]:
token = lookup(ch) # preloaded with appropriate token
elif ch.isdigit():
# In the real version, build number and don't forget to end with ungetch()
while(ch.isdigit() == True):
x = str(x) + str(ch)
ch = getch()
ch = ungetch()
token = symbol(x, number, value=int(x)) # simplistic SINGLE DIGIT Ascii to Binary
return
elif ch == '#':
str1 = ""
ch = getch()
while ch != " ":
str1 = str(str1) + str(ch)
ch = getch()
ch = getch()
# token = symbol(str1, commentstr, value=str(str1)) # simplistic SINGLE DIGIT Ascii to Binary
print("#comment: " + str(str1))
return
elif ch == '"':
a = ""
ch = getch()
counterafter1 = counterafter
i = counterafter
if counterafter != 700:
counterafter = counterafter + 4;
counterafter = i
while (ch != '"'):
a = str(a) + str(ch)
if ch != " ":
b = "'"+ch+"'"
emit(i, "constant",b)
ch = getch()
else:
ch = getch()
i=i+1
emit(i, "constant", 13)
emit(i+1, "constant", 0)
emit(i+2, "return", '')
ch = getch()
counterafter=i+3
token = symbol(a, stringsym, value=str(a)) # simplistic SINGLE DIGIT Ascii to Binary
return
elif ch == "<":
ch = getch()
if ch == "=":
lt = ""
lt = "<" + "="
token = symbol(lt, lessthanequal, value=str(lt)) # simplistic SINGLE DIGIT Ascii to Binary
return
else:
ch == ungetch()
token = symbol("<", lessthan, value="<") # simplistic SINGLE DIGIT Ascii to Binary
return
elif ch == "!":
ne = ""
ch = getch()
if ch == "=":
ne = "!" + "="
token = symbol(ne, jumpne, value=str(ne)) # simplistic SINGLE DIGIT Ascii to Binary
return
else:
ch == ungetch()
token = symbol("!", NOT , value="!") # simplistic SINGLE DIGIT Ascii to Binary
return
elif ch == "=":
eq = ""
ch = getch()
if ch == "=":
eq = "=" + "="
token = symbol(eq, jumpeq, value=str(eq)) # simplistic SINGLE DIGIT Ascii to Binary
return
else:
ch == ungetch()
token = symbol("=", assignsym, value="=") # simplistic SINGLE DIGIT Ascii to Binary
return
elif ch == ">":
gt = ""
ch = getch()
if ch == "=":
gt = ">" + "="
token = symbol(gt, greaterthanequal, value=str(gt)) # simplistic SINGLE DIGIT Ascii to Binary
return
else:
ch == ungetch()
token = symbol(">", greaterthan, value=">") # simplistic SINGLE DIGIT Ascii to Binary
return
else:
print "Unknown character -->%s<- decimal %d" % (ch, ord(ch))
sys.exit(1) # Abort Compilation
#======================================================================
# THE GRAMMAR
# <program> ::= { <id> ; <varDeclare > <stmtlist> }
# <varDeclare> ::= var { <id> ; } % DECLARATIONS
# <arraySub> ::= [<expr>]
# <stmtlist> ::= <stmt> { ; <stmt> }
# <stmt> ::= print <id>
# <id> = <expr>
# <expr> ::= <term> { (+ | - ) <term> }
# <term> ::= <factor> { (*|/) factor}
# <factor> ::= [+/-] ID | Number | expression
#======================================================================
# Centralised Parser Error Message handler
#======================================================================
#===============================================================================
def error (msg):
#===============================================================================
print line
print "-" * charIndex, "^"
print("Error on %d - %s\n" % (number, msg))
printToken(token)
print("\n")
#===============================================================================
def emit (memadr, opcode, parameter):
#===============================================================================
"""EMIT CODE - Emit a of code with a Parameter
if first arg is zero - (the memory address), use and incr CODEPTR"""
global codeptr
if (memadr == 0):
memadr = codeptr
codeptr = codeptr + 1
print "%6d %-8s %-7s" % (memadr, opcode, parameter)
#===============================================================================
def declareList() :
# declareList ::= varDeclare {, varDeclare};
#===============================================================================
varDeclare()
while token.token != semicolon :
if token.token == comma:
varDeclare()
getoken()
# else: error("comma or semicolon expected in declaration")
#===============================================================================
def varDeclare() :
# varDeclare ::= idsym [ = number | "[" number "]"
#===============================================================================
ta = 0
tn = []
global varptr;
global whichidaddress;
global arraySubaddress;
global arrstar;
getoken();
if token.token == idsym:
ta = token.address
tn = token.name
getoken()
if token.token == leftsquarebracket:
getoken()
if token.token == number: #number
print("#The address for "+ str(tn)+ " are ")
symtbl[tn].address = varptr;
# emit(0, "constant", varptr)
print("#"+str(varptr))
while (token.value != 0):
# print("#address at " + str(varptr))
varptr = varptr + 1
token.value= token.value-1
# emit(0, "constant", varptr)
print("#"+str(varptr))
# getoken()
getoken()
if token.token == rightsquarebracket:
getoken()
else:
error("Expected rightsquarebracket at the end of arraySub declare")
else:
if ta != 0:
print("#"),
print("%c already declared\n", tn);
# assignStmt()
else:
symtbl[tn].address = varptr;
varptr = varptr + 1;
# emit(0, "load", varptr)
"""
if token.token == assignsym:
getoken()
if token.token == number:
arraySubaddress = arrstar+token.value
whichidaddress = arraySubaddress
print"#"+"arraySub address", str(arraySubaddress)
getoken()
if token.token == rightsquarebracket:
stmt()
# getoken()
getoken()
"""
# if token.token == leftsquarebracket:
# varDeclare()
# getoken()
# if token.token == rightbracket:
# getoken()
#===============================================================================
def variable():
# idsym [arraySub]
#===============================================================================
if token.token == idsym:
arraySub()
#===============================================================================
def arraySub():
# [expression]
#===============================================================================
global arraySub;
expression()
#===============================================================================
def parameters():
#===============================================================================
varDeclare()
if token.token == comma:
varDeclare()
# getoken()
#======================================================================
# STMTLIST
# <stmtlist> ::= <stmt> { ; <stmt> }
#===============================================================================
def stmtList():
#===============================================================================
stmt()
while (token.token != rightbrace):
stmt()
#======================================================================
# STMT
#===============================================================================
def stmt():
#===============================================================================
""" <stmt> ::= print <expression|string>| read <varDeclare> | <id> = <expression> |
if <condition> <stmt> [else <stmt>]| while <condition> <stmt>|
<stmtList> | do <stmsList> forever | break | continue
"""
global codeptr
thisStmtAdr = codeptr # Jump DEMO - not part of Stmt
# if token.token == arraySubsym:
# arraySub()
if token.token == varDeclare:
getoken()
if token.token == assignsym:
expression()
else:
parameter()
elif token.token == ifsym:
ifStmt()
# elif token.token == elsesym:
# elseStmt()
elif token.token == whilesym:
whileStmt()
elif token.token == stmtList:
stmtList()
elif token.token == printsym:
printStmt()
elif token.token == readsym:
readStmt()
elif token.token == declaresym:
declareList()
elif token.token == dosym:
doStmt()
elif token.token == breaksym:
emit(0, "halt", '')
getoken()
elif token.token == continuesym:
continueStmt()
elif token.token == number:
expression()
elif token.token == idsym:
assignStmt()
elif token.token == functionsym:
function()
elif token.token == returnsym:
returnStmt()
else:
error("Expected start of a statement")
if token.token == semicolon or token.token == comma:
getoken()
#===============================================================================
def printStmt():
#===============================================================================
""" <printStmt> ::= print <expression|string>"""
global idaddress
getoken() # skip "print"
if token.token == leftbracket:
getoken()
else:
error("Expected leftbracket before the print-item")
# printta = token.address
print_item()
if token.token == comma:
print_item()
getoken()
if token.token == rightbracket:
getoken()
# if token.token == rightbracket:
# getoken()
# else:
# error("Expected rightbracket end the print")
if token.token == semicolon:
getoken()
# else:
# error("Expected semicolon end the print")
#===============================================================================
def print_item():
# expression | string
#===============================================================================
# expression
if token.token == idsym:
expression()
emit(0, "writeint", 0)
getoken()
# string
if token.token == stringsym:
printMsg()
getoken()
#===============================================================================
def printMsg():
#===============================================================================
""" <printMsg> ::= printMsg <expression>"""
emit(0, "loadv", counterafter1)
emit(0, "store", 1)
emit(0, "call", 400)
emit(400, "load-Ind", 0)
emit(401, "jumpeq", 405)
emit(402, "writech", 0)
emit(403, "increment", 1)
emit(404, "jump", 400)
emit(405, "return", '')
#===============================================================================
def readStmt():
#===============================================================================
""" <readStmt> ::= read variable()"""
global idaddress
getoken()
if token.token == leftbracket:
getoken()
else:
error("Expected leftbracket before the variable")
variable()
emit(0, "readint", idaddress)
if token.token == rightbracket:
getoken()
else:
error("Expected rightbracket after the variable")
#===============================================================================
def assignStmt():
#===============================================================================
"""
<id> = <expression>
"""
global tokennum
global resultnum
global whichidentifier
global whichidaddress
global arraySubaddress
whichidentifier = token.name # Remember which ID on Left
tempadd = token.address
if arraySubaddress != 0:
whichidaddress = token.address;
else:
whichidaddress = arraySubaddress;
getoken() # Get token after identifier
if token.token == assignsym:
getoken()
else:
error("Expected = in assignment statement")
expression()
passtoken = token.value
# print(str(whichidaddress))
emit(0, "store", tempadd)
"""
if whichidaddress == 0:
# print("#tokenaddress " + str(tempadd))
emit(0, "store", tempadd)
else:
symtbl[whichidentifier].value = tokennum
# print("#whichidaddress "+str(whichidaddress))
emit(0, "store", whichidaddress)
"""
getoken()
#===============================================================================
def ifStmt():
# <ifStmt> ::= if (condition) statement [else statement]
#===============================================================================
getoken() # skip "if"
if token.token == leftbracket:
getoken()
else:
error("Expected leftbracket at the start of if-condition")
condition()
# getoken()
if token.token == rightbracket:
getoken()
else:
error("Expected rightbracket at the end of if-condition")
if token.token == leftbrace:
getoken()
else:
error("Expected leftbrace at the start of if-statement")
stmtList()
getoken()
if token.token == rightbrace:
getoken()
# else:
# error("Expected rightbrace at the end of if-statement")
if token.token == elsesym:
getoken()
if token.token == leftbrace:
getoken()
else:
error("Expected leftbrace at the start of else-statement")
stmt()
getoken()
# emit(0, "cont", '')
if token.token == rightbrace:
getoken()
else:
error("Expected rightbrace at the end of else-statement")
#===============================================================================
def whileStmt():
#===============================================================================
""" <whileStmt> ::= while (condition)statement"""
getoken()# skip "while"
if token.token == leftbracket:
getoken()
else:
error("Expected leftbracket at the start of while-condition")
condition()
if token.token == rightbracket:
getoken()
else:
error("Expected rightbracket at the end of while-condition")
if token.token == leftbrace:
getoken()
else:
error("Expected leftbrace at the start of while-statement")
stmtList()
# emit(0,"jump",127)
if token.token == rightbrace:
getoken()
else:
error("Expected rightbrace at the end of while-statement")
#===============================================================================
def doStmt():
#===============================================================================
getoken()
stmtList()
#===============================================================================
def returnStmt():
#===============================================================================
getoken()
if token.token == leftbracket:
getoken()
if token.token == idsym:
expression()
# print("#"+str(token.value))
emit(0, "jump", 0)
if token.token == rightbracket:
getoken()
else:
error("Expected rightbracket for return-statement")
#===============================================================================
def condition():
# [not] conditional-expression
#===============================================================================
notsign = False;
if token.token == notsym:
notsign = True;
getoken()
if notsign == True:
emit(0, "Not", '')
conditionalexp()
else:
conditionalexp()
#===============================================================================
def conditionalexp():
#===============================================================================
expression()
relational_op()
#===============================================================================
def relational_op():
#===============================================================================
if token.token == lessthan or token.token == greaterthan or token.token == lessthanequal or token.token == greaterthanequal or token.token == jumpne or token.token == jumpeq:
op = token # remember -
getoken() # skip past -
emit(0, "store", 686) # Save current expression result
expression()
if op.token == lessthan:
emit(0, "store", 5)
emit(0, "load", 686)
emit(0, "compare", 5)
emit(0, "jumplt", 131)
emit(0, "jump", 152)
elif op.token == greaterthan:
emit(0, "store", 5)
emit(0, "load", 686)
emit(0, "compare", 5)
emit(0, "jumpgt", 152)
emit(0, "jump", 131)
elif op.token == lessthanequal:
emit(0, "store", 5)
emit(0, "load", 686)
emit(0, "compare", 5)
emit(0, "jumplt", 139)
emit(0, "jumpeq", 139)
emit(0, "jump", 153)
elif op.token == greaterthanequal:
emit(0, "store", 5)
emit(0, "load", 686)
emit(0, "compare", 5)
emit(0, "jumpgt", 139)
emit(0, "jumpeq", 139)
emit(0, "jump", 153)
elif op.token == jumpne:
emit(0, "store", 5)
emit(0, "load", 686)
emit(0, "compare", 5)
emit(0, "jumpne", 122)
emit(0, "jump", 119)
elif op.token == jumpeq:
emit(0, "store", 5)
emit(0, "load", 686)
emit(0, "compare", 5)
emit(0, "jumpeq", 119)
emit(0, "jump", 122)
#===============================================================================
def expression():
#===============================================================================
"""
Leaves result in ACC at runtime
Use addresses 687 as Temporary variables
<expression> ::= <factor> { (+ | -) <factor> } <- wrong
<expression> ::= <term> { (+ | -) <term> }
"""
global whichidentifier
global idaddress
global idvalue
if whichidentifier == None:
getoken()
else:
idaddress = symtbl[whichidentifier].address
idvalue = symtbl[whichidentifier].value
if token.token == leftbracket:
getoken()
term()
## 1st start==============================================================================
while token.token == plus or token.token == minus:
op = token # remember -
getoken() # skip past -
emit(0, "store", 687) # Save current result
term()
if op.token == plus:
emit(0, "add", 687)
elif op.token == minus: # Subtract - have to swap operand order
emit(0, "store", 5)
emit(0, "load", 687)
emit(0, "subtract", 5)
#===============================================================================
def term():
#===============================================================================
"""
term::= factor {(*|/) factor}
Use addresses 688 as Temporary variables
"""
global idaddress
factor()
while token.token == mpy or token.token == div:
op = token # remember -
getoken() # skip past -
emit(0, "store", 688) # Save term result
# save here xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
factor()
if op.token == mpy:
emit(0, "mpy", 688)
elif op.token == div:
emit(0, "store", 5)
emit(0, "load",688)
emit(0, "div", 5)
#===============================================================================
def factor():
#===============================================================================
"""
# FACTOR() - leaves result in ACC at runtime
<factor> ::= [+|-] identifier | number | (expression)
"""
global tokennum
global whichidentifier
global idaddress
global idvalue
tokensign = False
# [+|-] number
if token.token == plus:
getoken()
# - (unary)
elif token.token == minus:
tokensign=True
getoken()
if token.token == number:
if tokensign == True:
emit(0, "loadv", 0 - token.value)
getoken()
else:
emit(0, "loadv", token.value)
tokennum = token.value
getoken()
# identifier
elif token.token == idsym:
emit(0, "load", token.address)
idaddress = token.address
tempaddress = token.address
# print(str(tempaddress))
getoken()
if token.token == leftbracket:
getoken()
expression()
# emit(0, "store", 684)
if token.token == comma:
emit(0, "store", tempaddress+1)
getoken()
expression()
emit(0, "call", 419)
else:
emit(0, "store", tempaddress+2)
emit(0, "call", 410)
if token.token == rightbracket:
getoken()
else:
error("Expected rightbracket after the factor")
else:
error("Start Of Factor Expected")
#===============================================================================
def function():
#===============================================================================
global returnadd;
global codeptr
global endaddress
beginaddress = codeptr
# print(str(beginaddress))
if endaddress < 200:
codeptr = codeptr+400
elif endaddress > 400:
codeptr = endaddress
getoken()
if token.token == idsym:
getoken()
if token.token == leftbracket:
getoken()
if token.token == idsym:
parameters()
# elif token.token == number:
# print("#"+str(token.value))
else:
error("Function error : No_parameter_input_for_function")
if token.token == rightbracket:
getoken()
else:
error("Expected rightbracket for parameter")
if token.token == semicolon:
getoken()
else:
error("Expected semicolon after parameter")
if token.token == declaresym:
declareList()
"""
if token.token == semicolon:
getoken()
else:
error("Expected semicolon after declare variable")
"""
if token.token == leftbrace:
getoken()
stmtList()
if token.token == rightbrace:
getoken()
print ("#---Function Finished---")
endaddress = codeptr
#===============================================================================
def program():
#===============================================================================
global codeptr
beginaddress = codeptr
if token.token == leftbrace:
getoken()
if token.token == programsym:
getoken()
else: error("Program start with 'program' keyword")
if token.token == idsym:
getoken()
if token.token == semicolon:
getoken()
if token.token == declaresym :
declareList()
while token.token == functionsym:
function()
codeptr = beginaddress
if token.token == leftbrace:
getoken()
stmtList()
if token.token == rightbrace:
print "#***Compilation Finished****"
#======================================================================
def main():
#======================================================================
global line
global srcfile
global charIndex
initSymTbl()
with open("test.txt") as srcfile:
# out1file = open('output.obj','w')
line = srcfile.read()
# out1file.write("hello")
# print line
charIndex = 0
debugScanner = False
if debugScanner: # Scanner Test Routine - Read a line and display the tokens
getoken()
while token.token is not None: # Skeleton for testing Scanner
printToken(token)
# y = str(token)
# out1file.write(y)
getoken()
sys.exit(1)
else:
getoken() # Parse Program according to the grammar
program()
#===============================================================================
# Main Compiler starts here
#===============================================================================
print "#Microcompiler.py v0.2"
#emit(0, "load", 0)
main()
"""
srcfile = open('test.txt', 'r')
lexer = shlex.shlex(srcfile)
for token in lexer:
print repr(token)
"""
# getoken()
#=======================================================================
# *** That's it folks - written by Giovanni Moretti - April 27, 2011 ***
#=======================================================================
| [
[
1,
0,
0.0008,
0.0008,
0,
0.66,
0,
540,
0,
1,
0,
0,
540,
0,
0
],
[
14,
0,
0.0024,
0.0008,
0,
0.66,
0.0154,
777,
1,
0,
0,
0,
0,
3,
0
],
[
8,
0,
0.0101,
0.0097,
0,
0... | [
"import re",
"__author__ = 'YeeHin Kwok'",
"\"\"\" Giovanni's MicroCompiler Demo\n\n<program> ::= { <id> ; <varDeclare > <stmtlist> }\n<varDeclare> ::= V { <id> ; } % DECLARATIONS\n\n<stmtlist> ::= <stmt> { ; <stmt> }\n<stmt> ::= P <id> | <id... |
import re
__author__ = 'YeeHin Kwok'
""" MicroCompiler
<program> ::= program <id>; declare declareList; { StmtList}
<declareList> ::= varDeclare {, varDeclare};
<varDeclare> ::= idsym [ = number | "[" number "]"
<stmt> ::= variable( = expression | parameter) | <printStmt> ::= print "("<print_item>{,<print_item>}")"| if <condition> <stmt> [else <stmt>]|
<readStmt> ::= read "("variable")" | <id> = <expression> |
while <condition> <stmt>| <stmtList> | do <stmsList> forever | break | continue
<stmtlist> ::= <stmt> { ; <stmt> }
<print_item> ::= expression | string
<condition> ::= [not] <conditionalexp>
<conditionalexp> ::= <expression>[<relational_op> <expression>]
<relational_op> ::= <|<=|==|!=|>|>=
<expression> ::= <term> { (+ | -) <term> }
<term> ::= <factor> {(*|/) <factor>}
<factor> ::= [+|-] <id> | <number> | "("<expression>")"
<variable> ::= <id> [<arraySub>]
<arraySub> ::= "["<expression>"]"
<constnat> ::= <number>
<id> ::= A-Z{A-Z _ 0-9 ? }
"""
import sys
import shlex
#===============================================================================
# # Lexical Analyser - the "Scanner" - Define the TokenTypes
#===============================================================================
tokenNames = \
[ "unknownToken", "idsym", "assignsym", "leftbrace", "rightbrace",
"varDeclareym", "semicolon", "whilesym", "leftbracket", "rightbracket",
"printsym", "ifsym", "equals", "lessthan", "greaterthan",
"number", "plus", "minus", "mpy", "div", "elsesym", "declaresym", "forsym", "andsym", "elifsym", "dosym", "returnsym", "notsym",
"continuesym", "breaksym", "nonesym", "programsym", "functionsym", "leftsquarebracket", "rightsquarebracket",
"lessthanequal", "colon", "comma", "comment", "commentstr", "dot", " greaterthanequal", "jumpeq", "jumpne",
"andop", "orop", "quote ", "stringsym", "arraySubsym", "readsym", "endfile"]
# define the tokens as variables
unknownToken, idsym, assignsym, leftbrace, rightbrace, \
varDeclareym, semicolon, whilesym, leftbracket, rightbracket, \
printsym, ifsym, equals, lessthan, greaterthan, \
number, plus, minus, mpy, div, elsesym, declaresym, forsym, andsym, elifsym, dosym, returnsym, notsym, \
continuesym, breaksym, nonesym, programsym, functionsym, leftsquarebracket, rightsquarebracket, \
lessthanequal, colon, comma, comment, commentstr, dot, greaterthanequal, jumpeq, jumpne, \
andop, orop, quote, stringsym, arraySubsym, readsym, endfile = range(0, len(tokenNames))
#===============================================================================
class symbol:
#===============================================================================
name = None # String representation
token = None; # Corresponding token
address = 0; # For variables, their runtime address
value = None # on defined for numbers
def __init__(self, name, token, value=0):
self.name = name
self.token = token
self.address = 0 # for identifiers, their address
self.value = value # for numbers, their value
symtbl = {}; # The Symbol Table, a dictionary of symbols indexed by name
#======================================================================
# GLOBALS for output of Lexical Analyser
# Set by each call to GeToken()
token = None; # A symbol
line = "\n" # the complex source file as a string
charIndex = 0 # the position in the source
linenumber = 0 # The current number
tokennum = 0
whichidentifier = None;
arraySubaddress = 0;
endaddress = 0;
i = 700
j = 700
counterafter = i
counterafter1 = j
EOF = chr(0)
#======================================================================
# Run Time Code Generation Variables
varptr = 500 # Arbitrary base address of memory for variables
codeptr = 10 # Address to output next instruction (for code)
#===============================================================================
# Symbol Table Management Routines
#===============================================================================
#===============================================================================
def addToSymTbl (name, token):
#===============================================================================
symtbl[name] = symbol(name, token) # Add a new symbol to the dictionary
return symtbl[name]
#===============================================================================
def lookup (thisName):
#===============================================================================
"# Find a given identifier in the Symbol Table, Return the symtbl entry"
if symtbl.has_key(thisName): # thisName has been seen before
return symtbl[thisName] # return the symtbl entry
else: return None
#===============================================================================
def initSymTbl():
#===============================================================================
"# Initialise Symbol Table, and preload reserved words"
addToSymTbl('var', varDeclareym) # VAR
addToSymTbl('program', programsym)
addToSymTbl('function', functionsym)
addToSymTbl('while', whilesym) # WHILE
addToSymTbl('print', printsym) # PRINT
addToSymTbl('else', elsesym)
addToSymTbl('elif', elifsym)
addToSymTbl('if', ifsym)
addToSymTbl('declare', declaresym)
addToSymTbl('for', forsym)
addToSymTbl('None', nonesym)
addToSymTbl('continue', continuesym)
addToSymTbl('read', readsym) # READINT
addToSymTbl('do', dosym)
addToSymTbl('return', returnsym)
addToSymTbl('not', notsym)
# Now add symbols - NB only single character symbols are here
# multicharacter one like ">=" are still to do
addToSymTbl('=', assignsym)
addToSymTbl('#', comment)
addToSymTbl('<', lessthan)
addToSymTbl('>', greaterthan)
addToSymTbl('{', leftbrace)
addToSymTbl('}', rightbrace)
addToSymTbl('(', leftbracket)
addToSymTbl(')', rightbracket)
addToSymTbl('+', plus)
addToSymTbl('-', minus)
addToSymTbl(';', semicolon)
addToSymTbl('break', breaksym)
addToSymTbl('*', mpy)
addToSymTbl('/', div)
addToSymTbl('[', leftsquarebracket)
addToSymTbl(']', rightsquarebracket)
addToSymTbl(':', colon)
addToSymTbl(',', comma)
addToSymTbl('.', dot)
addToSymTbl('==', jumpeq)
addToSymTbl('!=', jumpne)
addToSymTbl('&&', andop)
addToSymTbl('||', orop)
addToSymTbl('"', quote)
addToSymTbl(EOF, endfile)
#===============================================================================
# Scanner Diagnostics
#===============================================================================
def printToken(tok):
#===============================================================================
" - display the specified token."
if tok.token == idsym:
print "Token = %10s, %-10s adr = %3d, val = %d" % \
(tokenNames[tok.token], tok.name, tok.address, tok.value)
elif tok.token == number:
print "Token = %10s %d" % (tokenNames[tok.token], tok.value)
else:
print "Token = %10s" % tokenNames[tok.token]
#==============================?=================================================
def dumpSymTbl():
#===============================================================================
""" Dump all the tokens in the symboltable """
print("# *** Symbol Table ***")
for name in symtbl.keys(): # keys is a list of the names (printable form of tokens)
tok = symtbl[name]
if tok.token == idsym:
print("#"),
printToken(tok)
#===============================================================================
def getch():
#===============================================================================
global line
global charIndex
global linenumber
while True:
if charIndex < len(line): # See if used up current line
ch = line[charIndex] # if not, get character
charIndex = charIndex + 1 # & move pointer for next time
else:
# line = f.readline()
if line == "": line = EOF
dumpSymTbl()
print "#End of File"
print "#--> ",
line = raw_input() + "\n" # read new line, adding \n so it's like f.readline()
# line = srcfile.read()
charIndex = 0 # & reset character pointer
linenumber = linenumber + 1
continue
if ch == "\n":
ch = " "
if ch == '?':
dumpSymTbl()
continue
return ch
#===============================================================================
def ungetch():
#===============================================================================
""" Unget the next character peeked at when building variables, numbers
and when distinguishing between >= and > ...
"""
global charIndex;
charIndex = charIndex - 1;
#===============================================================================
def getoken():
#===============================================================================
""" GETOKEN - Put next token into the global TOKEN """
global token
global i
global m
global counterafter
global counterafter1
x = 0
ch = getch() # skip whitespace
while ch in ["\t", " ", "\n"]:
ch = getch()
# If ch is alphabetic then this is start of reserved word or an identifier
if ch.isalpha(): # Letter therefore it's either identifier or reserved word
name = ""
while ch.isalpha() or ch.isdigit() or ch == "_":
name = name + ch
ch = getch()
ungetch() # let terminator be used next time
token = lookup(name) # See if token's known
if token is None: # if not
token = addToSymTbl(name, idsym) # add as 'idsym'-IDENTIFIER
return # we've set token.token to either id or tokentype of reserved word
elif ch in ["{", "}", "(", ")", "[", "]", "+", "-", "*", "/", ";", ",", ":", EOF]:
token = lookup(ch) # preloaded with appropriate token
elif ch.isdigit():
# In the real version, build number and don't forget to end with ungetch()
while(ch.isdigit() == True):
x = str(x) + str(ch)
ch = getch()
ch = ungetch()
token = symbol(x, number, value=int(x)) # simplistic SINGLE DIGIT Ascii to Binary
return
# If ch is #
elif ch == '#':
str1 = ""
ch = getch()
#End while if the comment have ""
while ch != " ":
str1 = str(str1) + str(ch)
ch = getch()
ch = getch()
print("#comment: " + str(str1))
return
# If ch is "
elif ch == '"':
a = ""
ch = getch()
counterafter1 = counterafter
i = counterafter
if counterafter != 700:
counterafter = counterafter + 4;
counterafter = i
while (ch != '"'):
a = str(a) + str(ch)
if ch != " ":
b = "'" + ch + "'"
emit(i, "constant", b)
ch = getch()
else:
ch = getch()
i = i + 1
emit(i, "constant", 13)
emit(i + 1, "constant", 0)
emit(i + 2, "return", '')
ch = getch()
counterafter = i + 3
token = symbol(a, stringsym, value=str(a)) # simplistic SINGLE DIGIT Ascii to Binary
return
# If ch is <
elif ch == "<":
ch = getch()
if ch == "=":
lt = ""
lt = "<" + "="
token = symbol(lt, lessthanequal, value=str(lt)) # simplistic SINGLE DIGIT Ascii to Binary
return
else:
ch == ungetch()
token = symbol("<", lessthan, value="<") # simplistic SINGLE DIGIT Ascii to Binary
return
# If ch is !
elif ch == "!":
ne = ""
ch = getch()
if ch == "=":
ne = "!" + "="
token = symbol(ne, jumpne, value=str(ne)) # simplistic SINGLE DIGIT Ascii to Binary
return
else:
ch == ungetch()
token = symbol("!", NOT , value="!") # simplistic SINGLE DIGIT Ascii to Binary
return
# If ch is =
elif ch == "=":
eq = ""
ch = getch()
if ch == "=":
eq = "=" + "="
token = symbol(eq, jumpeq, value=str(eq)) # simplistic SINGLE DIGIT Ascii to Binary
return
else:
ch == ungetch()
token = symbol("=", assignsym, value="=") # simplistic SINGLE DIGIT Ascii to Binary
return
# If ch is >
elif ch == ">":
gt = ""
ch = getch()
if ch == "=":
gt = ">" + "="
token = symbol(gt, greaterthanequal, value=str(gt)) # simplistic SINGLE DIGIT Ascii to Binary
return
else:
ch == ungetch()
token = symbol(">", greaterthan, value=">") # simplistic SINGLE DIGIT Ascii to Binary
return
else:
print "Unknown character -->%s<- decimal %d" % (ch, ord(ch))
sys.exit(1) # Abort Compilation
#======================================================================
# THE GRAMMAR
# <program> ::= program <id>; declare declareList; { StmtList}
# <declareList> ::= varDeclare {, varDeclare};
# <varDeclare> ::= idsym [ = number | "[" number "]"
# <stmt> ::= variable( = expression | parameter) | <printStmt> ::= print "("<print_item>{,<print_item>}")"| if <condition> <stmt> [else <stmt>]|
# <readStmt> ::= read "("variable")" | <id> = <expression> |
# while <condition> <stmt>| <stmtList> | do <stmsList> forever | break | continue
# <stmtlist> ::= <stmt> { ; <stmt> }
# <print_item> ::= expression | string
# <condition> ::= [not] <conditionalexp>
# <conditionalexp> ::= <expression>[<relational_op> <expression>]
# <relational_op> ::= <|<=|==|!=|>|>=
# <expression> ::= <term> { (+ | -) <term> }
# <term> ::= <factor> {(*|/) <factor>}
# <factor> ::= [+|-] <id> | <number> | "("<expression>")"
# <variable> ::= <id> [<arraySub>]
# <arraySub> ::= "["<expression>"]"
#======================================================================
# Centralised Parser Error Message handler
#======================================================================
#===============================================================================
def error (msg):
#===============================================================================
print line
print "-" * charIndex, "^"
print("Error on %d - %s\n" % (number, msg))
printToken(token)
print("\n")
#===============================================================================
def emit (memadr, opcode, parameter):
#===============================================================================
"""EMIT CODE - Emit a of code with a Parameter
if first arg is zero - (the memory address), use and incr CODEPTR"""
global codeptr
if (memadr == 0):
memadr = codeptr
codeptr = codeptr + 1
print "%6d %-8s %-7s" % (memadr, opcode, parameter)
#===============================================================================
def declareList() :
# declareList ::= varDeclare {, varDeclare};
#===============================================================================
varDeclare()
while token.token != semicolon :
if token.token == comma:
varDeclare()
getoken()
#===============================================================================
def varDeclare() :
# <varDeclare> ::= idsym [ = number | "[" number "]"
#===============================================================================
ta = 0
tn = []
global varptr;
global whichidaddress;
global arraySubaddress;
getoken();
if token.token == idsym:
ta = token.address
tn = token.name
getoken()
if token.token == leftsquarebracket:
getoken()
if token.token == number: # number
symtbl[tn].address = varptr;
while (token.value != 0):
varptr = varptr + 1
token.value = token.value - 1
getoken()
if token.token == rightsquarebracket:
getoken()
else:
error("Expected rightsquarebracket at the end of arraySub declare")
else:
if ta != 0:
print("#"),
print("%c already declared\n", tn);
# assignStmt()
else:
symtbl[tn].address = varptr;
varptr = varptr + 1;
# emit(0, "load", varptr)
#===============================================================================
def variable():
# <variable> ::= <id> [<arraySub>]
#===============================================================================
if token.token == idsym:
expression()
# getoken()
if token.token == leftsquarebracket:
arraySub()
#===============================================================================
def arraySub():
# <arraySub> ::= "["<expression>"]"
#===============================================================================
global arraySub;
expression()
if token.token == rightsquarebracket:
getoken()
else:
error("Expected rightsquarebracket for array expression")
#===============================================================================
def parameters():
#===============================================================================
varDeclare()
if token.token == comma:
varDeclare()
# getoken()
#======================================================================
# STMTLIST
# <stmtlist> ::= <stmt> { ; <stmt> }
#===============================================================================
def stmtList():
#===============================================================================
stmt()
while (token.token != rightbrace):
stmt()
#======================================================================
# STMT
# <stmt> ::= variable( = expression | parameter) | <printStmt> ::= print "("<print_item>{,<print_item>}")"| if <condition> <stmt> [else <stmt>]|
# <readStmt> ::= read "("variable")" | <id> = <expression> |
# while <condition> <stmt>| <stmtList> | do <stmsList> forever | break | continue
#===============================================================================
def stmt():
#===============================================================================
global codeptr
thisStmtAdr = codeptr # Jump DEMO - not part of Stmt
if token.token == variable:
getoken()
if token.token == assignsym:
expression()
else:
parameter()
elif token.token == ifsym:
ifStmt()
elif token.token == whilesym:
whileStmt()
elif token.token == stmtList:
stmtList()
elif token.token == printsym:
printStmt()
elif token.token == readsym:
readStmt()
elif token.token == declaresym:
declareList()
elif token.token == dosym:
doStmt()
elif token.token == breaksym:
emit(0, "halt", '')
getoken()
elif token.token == continuesym:
continueStmt()
elif token.token == number:
expression()
elif token.token == idsym:
assignStmt()
elif token.token == functionsym:
function()
elif token.token == returnsym:
returnStmt()
else:
error("Expected start of a statement")
if token.token == semicolon or token.token == comma:
getoken()
#===============================================================================
def printStmt():
# <printStmt> ::= print "("<print_item>{,<print_item>}")"
#===============================================================================
getoken() # skip "print"
if token.token == leftbracket:
getoken()
else:
error("Expected leftbracket before the print-item")
print_item()
if token.token == comma:
print_item()
getoken()
if token.token == rightbracket:
getoken()
if token.token == semicolon:
getoken()
#===============================================================================
def print_item():
# <print_item> ::= expression | string
#===============================================================================
# expression
if token.token == idsym:
expression()
emit(0, "writeint", 0)
getoken()
# string
if token.token == stringsym:
printMsg()
getoken()
#===============================================================================
def printMsg():
# <printMsg> ::= printMsg <expression>
#===============================================================================
emit(0, "loadv", counterafter1)
emit(0, "store", 1)
emit(0, "call", 400)
emit(400, "load-Ind", 0)
emit(401, "jumpeq", 405)
emit(402, "writech", 0)
emit(403, "increment", 1)
emit(404, "jump", 400)
emit(405, "return", '')
#===============================================================================
def readStmt():
# <readStmt> ::= read "("variable")"
#===============================================================================
global idaddress
getoken()
if token.token == leftbracket:
getoken()
else:
error("Expected leftbracket before the variable")
variable()
emit(0, "readint", idaddress)
if token.token == rightbracket:
getoken()
else:
error("Expected rightbracket after the variable")
#===============================================================================
def assignStmt():
#===============================================================================
"""
<id> = <expression>
"""
global tokennum
global whichidentifier
global whichidaddress
global arraySubaddress
whichidentifier = token.name # Remember which ID on Left
tempadd = token.address
if arraySubaddress != 0:
whichidaddress = token.address;
else:
whichidaddress = arraySubaddress;
getoken() # Get token after identifier
if token.token == assignsym:
getoken()
else:
error("Expected = in assignment statement")
expression()
passtoken = token.value
emit(0, "store", tempadd)
getoken()
#===============================================================================
def ifStmt():
# <ifStmt> ::= if (condition) statement [else statement]
#===============================================================================
getoken() # skip "if"
if token.token == leftbracket:
getoken()
else:
error("Expected leftbracket at the start of if-condition")
condition()
if token.token == rightbracket:
getoken()
else:
error("Expected rightbracket at the end of if-condition")
if token.token == leftbrace:
getoken()
else:
error("Expected leftbrace at the start of if-statement")
stmtList()
getoken()
if token.token == rightbrace:
getoken()
if token.token == elsesym:
getoken()
if token.token == leftbrace:
getoken()
else:
error("Expected leftbrace at the start of else-statement")
stmt()
getoken()
if token.token == rightbrace:
getoken()
else:
error("Expected rightbrace at the end of else-statement")
#===============================================================================
def whileStmt():
# <whileStmt> ::= while (condition)statement
#===============================================================================
getoken() # skip "while"
if token.token == leftbracket:
getoken()
else:
error("Expected leftbracket at the start of while-condition")
condition()
if token.token == rightbracket:
getoken()
else:
error("Expected rightbracket at the end of while-condition")
if token.token == leftbrace:
getoken()
else:
error("Expected leftbrace at the start of while-statement")
stmtList()
# emit(0,"jump",127)
if token.token == rightbrace:
getoken()
else:
error("Expected rightbrace at the end of while-statement")
#===============================================================================
def doStmt():
# doStmt ::= <do> stmtList <forever>
#===============================================================================
getoken()
stmtList()
#===============================================================================
def returnStmt():
#===============================================================================
getoken()
if token.token == leftbracket:
getoken()
if token.token == idsym:
expression()
emit(0, "jump", 0)
if token.token == rightbracket:
getoken()
else:
error("Expected rightbracket for return-statement")
#===============================================================================
def condition():
# condition ::= [not] conditional-expression
#===============================================================================
notsign = False;
if token.token == notsym:
notsign = True;
getoken()
if notsign == True:
emit(0, "Not", '')
conditionalexp()
else:
conditionalexp()
#===============================================================================
def conditionalexp():
# <conditionalexp> ::= <expression>[relational_op <expression>]
#===============================================================================
expression()
relational_op()
#===============================================================================
def relational_op():
# <relational_op> ::= <|<=|==|!=|>|>=
#===============================================================================
if token.token == lessthan or token.token == greaterthan or token.token == lessthanequal or token.token == greaterthanequal or token.token == jumpne or token.token == jumpeq:
op = token # remember -
getoken() # skip past -
emit(0, "store", 686) # Save current expression result
expression()
if op.token == lessthan:
emit(0, "store", 5)
emit(0, "load", 686)
emit(0, "compare", 5)
emit(0, "jumplt", 137)
emit(0, "jump", 158)
elif op.token == greaterthan:
emit(0, "store", 5)
emit(0, "load", 686)
emit(0, "compare", 5)
emit(0, "jumpgt", 158)
emit(0, "jump", 137)
elif op.token == lessthanequal:
emit(0, "store", 5)
emit(0, "load", 686)
emit(0, "compare", 5)
emit(0, "jumplt", 145)
emit(0, "jumpeq", 145)
emit(0, "jump", 159)
elif op.token == greaterthanequal:
emit(0, "store", 5)
emit(0, "load", 686)
emit(0, "compare", 5)
emit(0, "jumpgt", 145)
emit(0, "jumpeq", 145)
emit(0, "jump", 159)
elif op.token == jumpne:
emit(0, "store", 5)
emit(0, "load", 686)
emit(0, "compare", 5)
emit(0, "jumpne", 128)
emit(0, "jump", 125)
elif op.token == jumpeq:
emit(0, "store", 5)
emit(0, "load", 686)
emit(0, "compare", 5)
emit(0, "jumpeq", 125)
emit(0, "jump", 128)
#===============================================================================
def expression():
# <expression> ::= <term> { (+ | -) <term> }
#===============================================================================
"""
Leaves result in ACC at runtime
Use addresses 687 as Temporary variables
"""
global whichidentifier
global idaddress
global idvalue
if whichidentifier == None:
getoken()
else:
idaddress = symtbl[whichidentifier].address
idvalue = symtbl[whichidentifier].value
if token.token == leftbracket:
getoken()
term()
while token.token == plus or token.token == minus:
op = token # remember -
getoken() # skip past -
emit(0, "store", 687) # Save current result
term()
if op.token == plus:
emit(0, "add", 687)
elif op.token == minus: # Subtract - have to swap operand order
emit(0, "store", 5)
emit(0, "load", 687)
emit(0, "subtract", 5)
#===============================================================================
def term():
# <term> ::= <factor> {(*|/) <factor>}
#===============================================================================
"""
Use addresses 688 as Temporary variables
"""
factor()
while token.token == mpy or token.token == div:
op = token # remember -
getoken() # skip past -
emit(0, "store", 688) # Save term result
# save here xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
factor()
if op.token == mpy:
emit(0, "mpy", 688)
elif op.token == div:
emit(0, "store", 5)
emit(0, "load", 688)
emit(0, "div", 5)
#===============================================================================
def factor():
# <factor> ::= [+|-] <id> | <number> | "("<expression>")"
#===============================================================================
"""
# FACTOR() - leaves result in ACC at runtime
"""
global tokennum
global whichidentifier
global idaddress
global idvalue
tokensign = False
# [+|-] number
if token.token == plus:
getoken()
# - (unary)
elif token.token == minus:
tokensign = True
getoken()
# number
if token.token == number:
if tokensign == True:
emit(0, "loadv", 0 - token.value)
getoken()
else:
emit(0, "loadv", token.value)
tokennum = token.value
getoken()
# id
elif token.token == idsym:
emit(0, "load", token.address)
idaddress = token.address
tempaddress = token.address
getoken()
if token.token == leftbracket:
getoken()
expression()
if token.token == comma:
# For two parameters
emit(0, "store", tempaddress + 1)
getoken()
expression()
emit(0, "call", 419)
else:
# For one parameter
emit(0, "store", tempaddress + 2)
emit(0, "call", 410)
if token.token == rightbracket:
getoken()
else:
error("Expected rightbracket after the factor")
# "(" <expression> ")"
elif token.token == leftbracket:
emit(0, "store", 689)
emit(0, "push", 1)
getoken()
expression()
if token.token == rightbracket:
getoken()
emit(0, "pop", 1)
else:
error("Start Of Factor Expected")
#===============================================================================
def function():
#===============================================================================
global codeptr
global endaddress
beginaddress = codeptr
if endaddress < 200:
codeptr = codeptr + 400
elif endaddress > 400:
codeptr = endaddress
getoken()
if token.token == idsym:
getoken()
if token.token == leftbracket:
getoken()
if token.token == idsym:
parameters()
else:
error("Function error : No_parameter_input_for_function")
if token.token == rightbracket:
getoken()
else:
error("Expected rightbracket for parameter")
if token.token == semicolon:
getoken()
else:
error("Expected semicolon after parameter")
if token.token == declaresym:
declareList()
if token.token == leftbrace:
getoken()
stmtList()
if token.token == rightbrace:
getoken()
print ("#---Function Finished---")
endaddress = codeptr
#===============================================================================
def program():
# <program> ::= program <id>; declare declareList; { StmtList}
#===============================================================================
global codeptr
beginaddress = codeptr
if token.token == leftbrace:
getoken()
if token.token == programsym:
getoken()
else: error("Program start with 'program' keyword")
if token.token == idsym:
getoken()
if token.token == semicolon:
getoken()
if token.token == declaresym :
declareList()
while token.token == functionsym:
function()
codeptr = beginaddress
if token.token == leftbrace:
getoken()
stmtList()
if token.token == rightbrace:
print "#***Compilation Finished****"
#======================================================================
def main():
#======================================================================
global line
global srcfile
global charIndex
initSymTbl()
with open("test2.txt") as srcfile:
line = srcfile.read()
charIndex = 0
debugScanner = False
if debugScanner: # Scanner Test Routine - Read a line and display the tokens
getoken()
while token.token is not None: # Skeleton for testing Scanner
printToken(token)
getoken()
sys.exit(1)
else:
getoken() # Parse Program according to the grammar
program()
#===============================================================================
# Main Compiler starts here
#===============================================================================
print "#Microcompiler.py"
main()
"""
srcfile = open('test.txt', 'r')
lexer = shlex.shlex(srcfile)
for token in lexer:
print repr(token)
"""
| [
[
1,
0,
0.0008,
0.0008,
0,
0.66,
0,
540,
0,
1,
0,
0,
540,
0,
0
],
[
14,
0,
0.0025,
0.0008,
0,
0.66,
0.0164,
777,
1,
0,
0,
0,
0,
3,
0
],
[
8,
0,
0.0169,
0.0228,
0,
0... | [
"import re",
"__author__ = 'YeeHin Kwok'",
"\"\"\" MicroCompiler \n\n<program> ::= program <id>; declare declareList; { StmtList}\n<declareList> ::= varDeclare {, varDeclare};\n<varDeclare> ::= idsym [ = number | \"[\" number \"]\" \n\n<stmt> ::= variable( = expression | parameter) ... |
import re
__author__ = 'YeeHin Kwok'
""" MicroCompiler
<program> ::= program <id>; declare declareList; { StmtList}
<declareList> ::= varDeclare {, varDeclare};
<varDeclare> ::= idsym [ = number | "[" number "]"
<stmt> ::= variable( = expression | parameter) | <printStmt> ::= print "("<print_item>{,<print_item>}")"| if <condition> <stmt> [else <stmt>]|
<readStmt> ::= read "("variable")" | <id> = <expression> |
while <condition> <stmt>| <stmtList> | do <stmsList> forever | break | continue
<stmtlist> ::= <stmt> { ; <stmt> }
<print_item> ::= expression | string
<condition> ::= [not] <conditionalexp>
<conditionalexp> ::= <expression>[<relational_op> <expression>]
<relational_op> ::= <|<=|==|!=|>|>=
<expression> ::= <term> { (+ | -) <term> }
<term> ::= <factor> {(*|/) <factor>}
<factor> ::= [+|-] <id> | <number> | "("<expression>")"
<variable> ::= <id> [<arraySub>]
<arraySub> ::= "["<expression>"]"
<constnat> ::= <number>
<id> ::= A-Z{A-Z _ 0-9 ? }
"""
import sys
import shlex
#===============================================================================
# # Lexical Analyser - the "Scanner" - Define the TokenTypes
#===============================================================================
tokenNames = \
[ "unknownToken", "idsym", "assignsym", "leftbrace", "rightbrace",
"varDeclareym", "semicolon", "whilesym", "leftbracket", "rightbracket",
"printsym", "ifsym", "equals", "lessthan", "greaterthan",
"number", "plus", "minus", "mpy", "div", "elsesym", "declaresym", "forsym", "andsym", "elifsym", "dosym", "returnsym", "notsym",
"continuesym", "breaksym", "nonesym", "programsym", "functionsym", "leftsquarebracket", "rightsquarebracket",
"lessthanequal", "colon", "comma", "comment", "commentstr", "dot", " greaterthanequal", "jumpeq", "jumpne",
"andop", "orop", "quote ", "stringsym", "arraySubsym", "readsym", "endfile"]
# define the tokens as variables
unknownToken, idsym, assignsym, leftbrace, rightbrace, \
varDeclareym, semicolon, whilesym, leftbracket, rightbracket, \
printsym, ifsym, equals, lessthan, greaterthan, \
number, plus, minus, mpy, div, elsesym, declaresym, forsym, andsym, elifsym, dosym, returnsym, notsym, \
continuesym, breaksym, nonesym, programsym, functionsym, leftsquarebracket, rightsquarebracket, \
lessthanequal, colon, comma, comment, commentstr, dot, greaterthanequal, jumpeq, jumpne, \
andop, orop, quote, stringsym, arraySubsym, readsym, endfile = range(0, len(tokenNames))
#===============================================================================
class symbol:
#===============================================================================
name = None # String representation
token = None; # Corresponding token
address = 0; # For variables, their runtime address
value = None # on defined for numbers
def __init__(self, name, token, value=0):
self.name = name
self.token = token
self.address = 0 # for identifiers, their address
self.value = value # for numbers, their value
symtbl = {}; # The Symbol Table, a dictionary of symbols indexed by name
#======================================================================
# GLOBALS for output of Lexical Analyser
# Set by each call to GeToken()
token = None; # A symbol
line = "\n" # the complex source file as a string
charIndex = 0 # the position in the source
linenumber = 0 # The current number
tokennum = 0
whichidentifier = None;
arraySubaddress = 0;
endaddress = 0;
i = 700
j = 700
counterafter = i
counterafter1 = j
EOF = chr(0)
#======================================================================
# Run Time Code Generation Variables
varptr = 500 # Arbitrary base address of memory for variables
codeptr = 10 # Address to output next instruction (for code)
#===============================================================================
# Symbol Table Management Routines
#===============================================================================
#===============================================================================
def addToSymTbl (name, token):
#===============================================================================
symtbl[name] = symbol(name, token) # Add a new symbol to the dictionary
return symtbl[name]
#===============================================================================
def lookup (thisName):
#===============================================================================
"# Find a given identifier in the Symbol Table, Return the symtbl entry"
if symtbl.has_key(thisName): # thisName has been seen before
return symtbl[thisName] # return the symtbl entry
else: return None
#===============================================================================
def initSymTbl():
#===============================================================================
"# Initialise Symbol Table, and preload reserved words"
addToSymTbl('var', varDeclareym) # VAR
addToSymTbl('program', programsym)
addToSymTbl('function', functionsym)
addToSymTbl('while', whilesym) # WHILE
addToSymTbl('print', printsym) # PRINT
addToSymTbl('else', elsesym)
addToSymTbl('elif', elifsym)
addToSymTbl('if', ifsym)
addToSymTbl('declare', declaresym)
addToSymTbl('for', forsym)
addToSymTbl('None', nonesym)
addToSymTbl('continue', continuesym)
addToSymTbl('read', readsym) # READINT
addToSymTbl('do', dosym)
addToSymTbl('return', returnsym)
addToSymTbl('not', notsym)
# Now add symbols - NB only single character symbols are here
# multicharacter one like ">=" are still to do
addToSymTbl('=', assignsym)
addToSymTbl('#', comment)
addToSymTbl('<', lessthan)
addToSymTbl('>', greaterthan)
addToSymTbl('{', leftbrace)
addToSymTbl('}', rightbrace)
addToSymTbl('(', leftbracket)
addToSymTbl(')', rightbracket)
addToSymTbl('+', plus)
addToSymTbl('-', minus)
addToSymTbl(';', semicolon)
addToSymTbl('break', breaksym)
addToSymTbl('*', mpy)
addToSymTbl('/', div)
addToSymTbl('[', leftsquarebracket)
addToSymTbl(']', rightsquarebracket)
addToSymTbl(':', colon)
addToSymTbl(',', comma)
addToSymTbl('.', dot)
addToSymTbl('==', jumpeq)
addToSymTbl('!=', jumpne)
addToSymTbl('&&', andop)
addToSymTbl('||', orop)
addToSymTbl('"', quote)
addToSymTbl(EOF, endfile)
#===============================================================================
# Scanner Diagnostics
#===============================================================================
def printToken(tok):
#===============================================================================
" - display the specified token."
if tok.token == idsym:
print "Token = %10s, %-10s adr = %3d, val = %d" % \
(tokenNames[tok.token], tok.name, tok.address, tok.value)
elif tok.token == number:
print "Token = %10s %d" % (tokenNames[tok.token], tok.value)
else:
print "Token = %10s" % tokenNames[tok.token]
#==============================?=================================================
def dumpSymTbl():
#===============================================================================
""" Dump all the tokens in the symboltable """
print("# *** Symbol Table ***")
for name in symtbl.keys(): # keys is a list of the names (printable form of tokens)
tok = symtbl[name]
if tok.token == idsym:
print("#"),
printToken(tok)
#===============================================================================
def getch():
#===============================================================================
global line
global charIndex
global linenumber
while True:
if charIndex < len(line): # See if used up current line
ch = line[charIndex] # if not, get character
charIndex = charIndex + 1 # & move pointer for next time
else:
# line = f.readline()
if line == "": line = EOF
# dumpSymTbl()
print "#End of File"
print "#--> ",
line = raw_input() + "\n" # read new line, adding \n so it's like f.readline()
# line = srcfile.read()
charIndex = 0 # & reset character pointer
linenumber = linenumber + 1
continue
if ch == "\n":
ch = " "
if ch == '?':
dumpSymTbl()
continue
return ch
#===============================================================================
def ungetch():
#===============================================================================
""" Unget the next character peeked at when building variables, numbers
and when distinguishing between >= and > ...
"""
global charIndex;
charIndex = charIndex - 1;
#===============================================================================
def getoken():
#===============================================================================
""" GETOKEN - Put next token into the global TOKEN """
global token
global i
global m
global counterafter
global counterafter1
x = 0
ch = getch() # skip whitespace
while ch in ["\t", " ", "\n"]:
ch = getch()
# If ch is alphabetic then this is start of reserved word or an identifier
if ch.isalpha(): # Letter therefore it's either identifier or reserved word
name = ""
while ch.isalpha() or ch.isdigit() or ch == "_":
name = name + ch
ch = getch()
ungetch() # let terminator be used next time
token = lookup(name) # See if token's known
if token is None: # if not
token = addToSymTbl(name, idsym) # add as 'idsym'-IDENTIFIER
return # we've set token.token to either id or tokentype of reserved word
elif ch in ["{", "}", "(", ")", "[", "]", "+", "-", "*", "/", ";", ",", ":", EOF]:
token = lookup(ch) # preloaded with appropriate token
elif ch.isdigit():
# In the real version, build number and don't forget to end with ungetch()
while(ch.isdigit() == True):
x = str(x) + str(ch)
ch = getch()
ch = ungetch()
token = symbol(x, number, value=int(x)) # simplistic SINGLE DIGIT Ascii to Binary
return
# If ch is #
elif ch == '#':
str1 = ""
ch = getch()
#End while if the comment have ""
while ch != " ":
str1 = str(str1) + str(ch)
ch = getch()
ch = getch()
print("#comment: " + str(str1))
return
# If ch is "
elif ch == '"':
a = ""
ch = getch()
counterafter1 = counterafter
i = counterafter
if counterafter != 700:
counterafter = counterafter + 4;
counterafter = i
while (ch != '"'):
a = str(a) + str(ch)
if ch != " ":
b = "'" + ch + "'"
emit(i, "constant", b)
ch = getch()
else:
ch = getch()
i = i + 1
emit(i, "constant", 13)
emit(i + 1, "constant", 0)
ch = getch()
counterafter = i + 3
token = symbol(a, stringsym, value=str(a)) # simplistic SINGLE DIGIT Ascii to Binary
return
# If ch is <
elif ch == "<":
ch = getch()
if ch == "=":
lt = ""
lt = "<" + "="
token = symbol(lt, lessthanequal, value=str(lt)) # simplistic SINGLE DIGIT Ascii to Binary
return
else:
ch == ungetch()
token = symbol("<", lessthan, value="<") # simplistic SINGLE DIGIT Ascii to Binary
return
# If ch is !
elif ch == "!":
ne = ""
ch = getch()
if ch == "=":
ne = "!" + "="
token = symbol(ne, jumpne, value=str(ne)) # simplistic SINGLE DIGIT Ascii to Binary
return
else:
ch == ungetch()
token = symbol("!", NOT , value="!") # simplistic SINGLE DIGIT Ascii to Binary
return
# If ch is =
elif ch == "=":
eq = ""
ch = getch()
if ch == "=":
eq = "=" + "="
token = symbol(eq, jumpeq, value=str(eq)) # simplistic SINGLE DIGIT Ascii to Binary
return
else:
ch == ungetch()
token = symbol("=", assignsym, value="=") # simplistic SINGLE DIGIT Ascii to Binary
return
# If ch is >
elif ch == ">":
gt = ""
ch = getch()
if ch == "=":
gt = ">" + "="
token = symbol(gt, greaterthanequal, value=str(gt)) # simplistic SINGLE DIGIT Ascii to Binary
return
else:
ch == ungetch()
token = symbol(">", greaterthan, value=">") # simplistic SINGLE DIGIT Ascii to Binary
return
else:
print "Unknown character -->%s<- decimal %d" % (ch, ord(ch))
sys.exit(1) # Abort Compilation
#======================================================================
# THE GRAMMAR
# <program> ::= program <id>; declare declareList; { StmtList}
# <declareList> ::= varDeclare {, varDeclare};
# <varDeclare> ::= idsym [ = number | "[" number "]"
# <stmt> ::= variable( = expression | parameter) | <printStmt> ::= print "("<print_item>{,<print_item>}")"| if <condition> <stmt> [else <stmt>]|
# <readStmt> ::= read "("variable")" | <id> = <expression> |
# while <condition> <stmt>| <stmtList> | do <stmsList> forever | break | continue
# <stmtlist> ::= <stmt> { ; <stmt> }
# <print_item> ::= expression | string
# <condition> ::= [not] <conditionalexp>
# <conditionalexp> ::= <expression>[<relational_op> <expression>]
# <relational_op> ::= <|<=|==|!=|>|>=
# <expression> ::= <term> { (+ | -) <term> }
# <term> ::= <factor> {(*|/) <factor>}
# <factor> ::= [+|-] <id> | <number> | "("<expression>")"
# <variable> ::= <id> [<arraySub>]
# <arraySub> ::= "["<expression>"]"
#======================================================================
# Centralised Parser Error Message handler
#======================================================================
#===============================================================================
def error (msg):
#===============================================================================
print line
print "-" * charIndex, "^"
print("Error on %d - %s\n" % (number, msg))
printToken(token)
print("\n")
#===============================================================================
def emit (memadr, opcode, parameter):
#===============================================================================
"""EMIT CODE - Emit a of code with a Parameter
if first arg is zero - (the memory address), use and incr CODEPTR"""
global codeptr
if (memadr == 0):
memadr = codeptr
codeptr = codeptr + 1
print "%6d %-8s %-7s" % (memadr, opcode, parameter)
#===============================================================================
def declareList() :
# declareList ::= varDeclare {, varDeclare};
#===============================================================================
varDeclare()
while token.token != semicolon :
if token.token == comma:
varDeclare()
getoken()
#===============================================================================
def varDeclare() :
# <varDeclare> ::= idsym [ = number | "[" number "]"
#===============================================================================
ta = 0
tn = []
global varptr;
global whichidaddress;
global arraySubaddress;
getoken();
if token.token == idsym:
ta = token.address
tn = token.name
getoken()
if token.token == leftsquarebracket:
getoken()
if token.token == number: # number
symtbl[tn].address = varptr;
while (token.value != 0):
varptr = varptr + 1
token.value = token.value - 1
getoken()
if token.token == rightsquarebracket:
getoken()
else:
error("Expected rightsquarebracket at the end of arraySub declare")
else:
if ta != 0:
print("#"),
print("%c already declared\n", tn);
# assignStmt()
else:
symtbl[tn].address = varptr;
varptr = varptr + 1;
# emit(0, "load", varptr)
#===============================================================================
def variable():
# <variable> ::= <id> [<arraySub>]
#===============================================================================
if token.token == idsym:
expression()
# getoken()
if token.token == leftsquarebracket:
arraySub()
#===============================================================================
def arraySub():
# <arraySub> ::= "["<expression>"]"
#===============================================================================
global arraySub;
expression()
if token.token == rightsquarebracket:
getoken()
else:
error("Expected rightsquarebracket for array expression")
#===============================================================================
def parameters():
#===============================================================================
varDeclare()
if token.token == comma:
varDeclare()
# getoken()
#======================================================================
# STMTLIST
# <stmtlist> ::= <stmt> { ; <stmt> }
#===============================================================================
def stmtList():
#===============================================================================
stmt()
while (token.token != rightbrace):
stmt()
#======================================================================
# STMT
# <stmt> ::= variable( = expression | parameter) | <printStmt> ::= print "("<print_item>{,<print_item>}")"| if <condition> <stmt> [else <stmt>]|
# <readStmt> ::= read "("variable")" | <id> = <expression> |
# while <condition> <stmt>| <stmtList> | do <stmsList> forever | break | continue
#===============================================================================
def stmt():
#===============================================================================
global codeptr
thisStmtAdr = codeptr # Jump DEMO - not part of Stmt
if token.token == variable:
getoken()
if token.token == assignsym:
expression()
else:
parameter()
elif token.token == ifsym:
ifStmt()
elif token.token == whilesym:
whileStmt()
elif token.token == printsym:
printStmt()
elif token.token == readsym:
readStmt()
elif token.token == declaresym:
declareList()
elif token.token == dosym:
doStmt()
elif token.token == breaksym:
# emit(0, "halt", '')
getoken()
elif token.token == continuesym:
continueStmt()
elif token.token == number:
expression()
elif token.token == idsym:
assignStmt()
elif token.token == functionsym:
function()
elif token.token == returnsym:
returnStmt()
elif token.token == leftbrace:
getoken()
stmtList()
else:
error("Expected start of a statement")
if token.token == semicolon:
getoken()
#===============================================================================
def printStmt():
# <printStmt> ::= print "("<print_item>{,<print_item>}")"
#===============================================================================
getoken() # skip "print"
if token.token == leftbracket:
getoken()
else:
error("Expected leftbracket before the print-item")
print_item()
# while (token.token != rightbracket):
# print_item()
if token.token != rightbracket:
print_item()
getoken()
# if token.token == semicolon:
# getoken()
#===============================================================================
def print_item():
# <print_item> ::= expression | string
#===============================================================================
# expression
if token.token == idsym:
expression()
emit(0, "writeint", 0)
getoken()
# string
elif token.token == stringsym:
printMsg()
getoken()
#===============================================================================
def printMsg():
# <printMsg> ::= printMsg <expression>
#===============================================================================
emit(0, "loadv", counterafter1)
emit(0, "store", 1)
emit(0, "call", 400)
emit(400, "load-Ind", 0)
emit(401, "jumpeq", 405)
emit(402, "writech", 0)
emit(403, "increment", 1)
emit(404, "jump", 400)
emit(405, "return", '')
#===============================================================================
def readStmt():
# <readStmt> ::= read "("variable")"
#===============================================================================
global idaddress
getoken()
if token.token == leftbracket:
getoken()
else:
error("Expected leftbracket before the variable")
variable()
emit(0, "readint", idaddress)
if token.token == rightbracket:
getoken()
else:
error("Expected rightbracket after the variable")
#===============================================================================
def assignStmt():
#===============================================================================
"""
<id> = <expression>
"""
global tokennum
global whichidentifier
global whichidaddress
global arraySubaddress
whichidentifier = token.name # Remember which ID on Left
tempadd = token.address
if arraySubaddress != 0:
whichidaddress = token.address;
else:
whichidaddress = arraySubaddress;
getoken() # Get token after identifier
if token.token == assignsym:
getoken()
else:
error("Expected = in assignment statement")
expression()
passtoken = token.value
emit(0, "store", tempadd)
getoken()
#===============================================================================
def ifStmt():
# <ifStmt> ::= if (condition) statement [else statement]
#===============================================================================
getoken() # skip "if"
if token.token == leftbracket:
getoken()
else:
error("Expected leftbracket at the start of if-condition")
ifStmtAdr = codeptr
condition()
if token.token == rightbracket:
getoken()
else:
error("Expected rightbracket at the end of if-condition")
emit(0, "load-Ind", 1)
#jump out of statement (300) if condition is false
emit(0, "jumpne", 300)
stmt()
#jump out of statement
emit(0, "jump",301)
if token.token == rightbrace:
getoken()
if token.token == elsesym:
getoken()
endptr1 = codeptr
#jump out of statement
emit(300, "jump",endptr1)
stmt()
if token.token == rightbrace:
getoken()
else:
error("Expected rightbrace at the end of else-statement")
endptr2 = codeptr
emit(301, "jump",endptr2)
#===============================================================================
def whileStmt():
# <whileStmt> ::= while (condition)statement
#===============================================================================
global whileStmtAdr
getoken() # skip "while"
if token.token == leftbracket:
getoken()
else:
error("Expected leftbracket at the start of while-condition")
#save while statment address
whileStmtAdr = codeptr
condition()
if token.token == rightbracket:
getoken()
else:
error("Expected rightbracket at the end of while-condition")
emit(0, "load-Ind", 1)
#jump out of statement (302) if condition is false
emit(0, "jumpne", 302)
stmt()
emit(0,"jump",whileStmtAdr)
endptr3 = codeptr
emit(302, "jump",endptr3)
if token.token == rightbrace:
getoken()
else:
error("Expected rightbrace at the end of while-statement")
#===============================================================================
def doStmt():
# doStmt ::= <do> stmtList <forever>
#===============================================================================
getoken()
stmtList()
#===============================================================================
def returnStmt():
#===============================================================================
getoken()
if token.token == leftbracket:
getoken()
if token.token == idsym:
expression()
emit(0, "return", '')
if token.token == rightbracket:
getoken()
else:
error("Expected rightbracket for return-statement")
#===============================================================================
def condition():
# condition ::= [not] conditional-expression
#===============================================================================
notsign = False;
if token.token == notsym:
notsign = True;
getoken()
if notsign == True:
emit(0, "Not", '')
conditionalexp()
else:
conditionalexp()
#===============================================================================
def conditionalexp():
# <conditionalexp> ::= <expression>[relational_op <expression>]
#===============================================================================
expression()
relational_op()
#===============================================================================
def relational_op():
# <relational_op> ::= <|<=|==|!=|>|>=
#===============================================================================
global endAdr
if token.token == lessthan or token.token == greaterthan or token.token == lessthanequal or token.token == greaterthanequal or token.token == jumpne or token.token == jumpeq:
op = token # remember -
getoken() # skip past -
emit(0, "store", 686) # Save current expression result
expression()
if op.token == lessthan:
emit(0, "store", 5)
emit(0, "load", 686)
emit(0, "compare", 5)
emit(0, "jumplt", codeptr+4)
#If False set X as 1
emit(0, "loadv", 1)
emit(0, "store-Ind", 1)
emit(0, "jump", codeptr+3)
#If True set X as 0
emit(0, "loadv", 0)
emit(0, "store-Ind", 1)
elif op.token == greaterthan:
emit(0, "store", 5)
emit(0, "load", 686)
emit(0, "compare", 5)
emit(0, "jumpgt", codeptr+4)
#If False set X as 1
emit(0, "loadv", 1)
emit(0, "store-Ind", 1)
emit(0, "jump", codeptr+3)
#If True set X as 0
emit(0, "loadv", 0)
emit(0, "store-Ind", 1)
elif op.token == lessthanequal:
emit(0, "store", 5)
emit(0, "load", 686)
emit(0, "compare", 5)
emit(0, "jumplt", codeptr+5)
emit(0, "jumpeq", codeptr+4)
#If False set X as 1
emit(0, "loadv", 1)
emit(0, "store-Ind", 1)
emit(0, "jump", codeptr+3)
#If True set X as 0
emit(0, "loadv", 0)
emit(0, "store-Ind", 1)
elif op.token == greaterthanequal:
emit(0, "store", 5)
emit(0, "load", 686)
emit(0, "compare", 5)
emit(0, "jumpgt", codeptr+5)
emit(0, "jumpeq", codeptr+4)
#If False set X as 1
emit(0, "loadv", 1)
emit(0, "store-Ind", 1)
emit(0, "jump", codeptr+3)
#If True set X as 0
emit(0, "loadv", 0)
emit(0, "store-Ind", 1)
elif op.token == jumpne:
emit(0, "store", 5)
emit(0, "load", 686)
emit(0, "compare", 5)
emit(0, "jumpne", codeptr+4)
#If False set X as 1
emit(0, "loadv", 1)
emit(0, "store-Ind", 1)
emit(0, "jump", codeptr+3)
#If True set X as 0
emit(0, "loadv", 0)
emit(0, "store-Ind", 1)
elif op.token == jumpeq:
emit(0, "store", 5)
emit(0, "load", 686)
emit(0, "compare", 5)
emit(0, "jumpeq", codeptr+4)
#If False set X as 0
emit(0, "loadv", 0)
emit(0, "store-Ind", 1)
emit(0, "jump", codeptr+3)
#If True set X as 1
emit(0, "loadv", 1)
emit(0, "store-Ind", 1)
#===============================================================================
def expression():
# <expression> ::= <term> { (+ | -) <term> }
#===============================================================================
"""
Leaves result in ACC at runtime
Use addresses 687 as Temporary variables
"""
global whichidentifier
global idaddress
global idvalue
if whichidentifier == None:
getoken()
else:
idaddress = symtbl[whichidentifier].address
idvalue = symtbl[whichidentifier].value
if token.token == leftbracket:
getoken()
term()
while token.token == plus or token.token == minus:
op = token # remember -
getoken() # skip past -
emit(0, "store", 687) # Save current result
term()
if op.token == plus:
emit(0, "add", 687)
elif op.token == minus: # Subtract - have to swap operand order
emit(0, "store", 5)
emit(0, "load", 687)
emit(0, "subtract", 5)
#===============================================================================
def term():
# <term> ::= <factor> {(*|/) <factor>}
#===============================================================================
"""
Use addresses 688 as Temporary variables
"""
factor()
while token.token == mpy or token.token == div:
op = token # remember -
getoken() # skip past -
emit(0, "store", 688) # Save term result
# save here xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
factor()
if op.token == mpy:
emit(0, "mpy", 688)
elif op.token == div:
emit(0, "store", 5)
emit(0, "load", 688)
emit(0, "div", 5)
#===============================================================================
def factor():
# <factor> ::= [+|-] <id> | <number> | "("<expression>")"
#===============================================================================
"""
# FACTOR() - leaves result in ACC at runtime
"""
global tokennum
global whichidentifier
global idaddress
global idvalue
tokensign = False
# [+|-] number
if token.token == plus:
getoken()
# - (unary)
elif token.token == minus:
tokensign = True
getoken()
# number
if token.token == number:
if tokensign == True:
emit(0, "loadv", 0 - token.value)
getoken()
else:
emit(0, "loadv", token.value)
tokennum = token.value
getoken()
# id
elif token.token == idsym:
emit(0, "load", token.address)
idaddress = token.address
tempaddress = token.address
getoken()
if token.token == leftbracket:
getoken()
expression()
if token.token == comma:
# For two parameters
emit(0, "store", tempaddress + 1)
getoken()
expression()
emit(0, "call", 419)
else:
# For one parameter
emit(0, "store", tempaddress + 2)
emit(0, "call", 410)
if token.token == rightbracket:
getoken()
else:
error("Expected rightbracket after the factor")
# "(" <expression> ")"
elif token.token == leftbracket:
emit(0, "store", 689)
emit(0, "push", 1)
getoken()
expression()
if token.token == rightbracket:
getoken()
emit(0, "pop", 1)
else:
error("Start Of Factor Expected")
#===============================================================================
def function():
#===============================================================================
global codeptr
global endaddress
beginaddress = codeptr
if endaddress < 200:
codeptr = codeptr + 400
elif endaddress > 400:
codeptr = endaddress
getoken()
if token.token == idsym:
getoken()
if token.token == leftbracket:
getoken()
if token.token == idsym:
parameters()
else:
error("Function error : No_parameter_input_for_function")
if token.token == rightbracket:
getoken()
else:
error("Expected rightbracket for parameter")
if token.token == semicolon:
getoken()
else:
error("Expected semicolon after parameter")
if token.token == declaresym:
declareList()
if token.token == leftbrace:
getoken()
stmtList()
if token.token == rightbrace:
getoken()
print ("#---Function Finished---")
endaddress = codeptr
#===============================================================================
def program():
# <program> ::= program <id>; declare declareList; { StmtList}
#===============================================================================
global codeptr
beginaddress = codeptr
if token.token == leftbrace:
getoken()
if token.token == programsym:
getoken()
else: error("Program start with 'program' keyword")
if token.token == idsym:
getoken()
if token.token == semicolon:
getoken()
if token.token == declaresym :
declareList()
while token.token == functionsym:
function()
codeptr = beginaddress
if token.token == leftbrace:
getoken()
stmtList()
if token.token == rightbrace:
print "#***Compilation Finished****"
#======================================================================
def main():
#======================================================================
global line
global srcfile
global charIndex
initSymTbl()
with open("combine.txt") as srcfile:
line = srcfile.read()
charIndex = 0
debugScanner = False
if debugScanner: # Scanner Test Routine - Read a line and display the tokens
getoken()
while token.token is not None: # Skeleton for testing Scanner
printToken(token)
getoken()
sys.exit(1)
else:
getoken() # Parse Program according to the grammar
program()
#===============================================================================
# Main Compiler starts here
#===============================================================================
print "#Microcompiler.py"
main()
"""
srcfile = open('test.txt', 'r')
lexer = shlex.shlex(srcfile)
for token in lexer:
print repr(token)
"""
| [
[
1,
0,
0.0008,
0.0008,
0,
0.66,
0,
540,
0,
1,
0,
0,
540,
0,
0
],
[
14,
0,
0.0024,
0.0008,
0,
0.66,
0.0164,
777,
1,
0,
0,
0,
0,
3,
0
],
[
8,
0,
0.0163,
0.022,
0,
0.... | [
"import re",
"__author__ = 'YeeHin Kwok'",
"\"\"\" MicroCompiler \n\n<program> ::= program <id>; declare declareList; { StmtList}\n<declareList> ::= varDeclare {, varDeclare};\n<varDeclare> ::= idsym [ = number | \"[\" number \"]\" \n\n<stmt> ::= variable( = expression | parameter) ... |
'''
Created on Jun 16, 2014
@author: Brian
'''
#filename:Lexer.py
import sys
flag=0
keyword=[]
keyword.extend(['program','var','begin','end','integer','if','then',
'else','while','do','read','write','procedure','function'])
simpleword='+-*/,;()[]'
doubleword='><=!:'
filename=raw_input('Please input the source filename(and path):\n');
try:
fin=open(filename,'r')
except:
print 'source file open error!\n'
sys.exit()
filename=raw_input('Please input the destination filename(and path):\n')
try:
fout=open(filename,'w')
except:
print 'destination file open error!\n'
source=fin.read()
print source
i=0
while i <len(source):
while source[i]==' ' or source[i]=='\t' or source[i]=='\n':
i=i+1
if source[i].isalpha():
temp=source[i]
i=i+1
while source[i].isalpha() or source[i].isdigit():
temp=temp+source[i]
i=i+1
if keyword.count(temp)==0:
if len(temp)>8:
temp=temp[0,7]
print 'warning: sysmol name length>8'
fout.write('ID\t'+temp)
fout.write('\n')
else:
fout.write(temp+'\t'+temp)
fout.write('\n')
elif source[i].isdigit():
temp=source[i]
i=i+1
while source[i].isdigit():
temp=temp+source[i]
i=i+1
fout.write('int\t'+temp)
fout.write('\n')
elif simpleword.count(source[i])==1:
fout.write(source[i]+'\t'+source[i])
fout.write('\n')
i=i+1
elif doubleword.count(source[i])==1:
temp=source[i]
i=i+1
if source[i]=='=':
temp=temp+'='
i=i+1
fout.write(temp+'\t'+temp)
fout.write('\n')
elif source[i]=='{':
i=1+1
while source[i]!='}':
i=i+1
i=i+1
else:
flag=flag+1
print 'Error,Program exit!\n'
break
print('%d,%d',i,len(source))
if flag==0:
print 'Success!\n' | [
[
8,
0,
0.039,
0.0649,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0909,
0.013,
0,
0.66,
0.0667,
509,
0,
1,
0,
0,
509,
0,
0
],
[
14,
0,
0.1039,
0.013,
0,
0.66,
... | [
"'''\nCreated on Jun 16, 2014\n\n@author: Brian\n'''",
"import sys",
"flag=0",
"keyword=[]",
"keyword.extend(['program','var','begin','end','integer','if','then',\n'else','while','do','read','write','procedure','function'])",
"simpleword='+-*/,;()[]'",
"doubleword='><=!:'",
"filename=raw_input('Please... |
""" Giovanni's MicroCompiler Demo
<program> ::= { <id> ; <vars > <stmtlist> }
<vars> ::= V { <id> ; } % DECLARATIONS
<stmtlist> ::= <stmt> { ; <stmt> }
<stmt> ::= P <id> | <id> = <expr>
<expr> ::= <factor> { (+ | -) <factor> } % No precedence
<factor> ::= ID | Number
"""
import sys
#===============================================================================
# # Lexical Analyser - the "Scanner" - Define the TokenTypes
#===============================================================================
tokenNames =\
[ "unknownToken", "idsym", "assignsym", "leftbrace", "rightbrace",
"varsym", "semicolon", "whilesym", "leftbracket", "rightbracket",
"printsym", "ifsym", "equals", "notequals", "lessthan", "greaterthan",
"number", "plus", "minus", "endfile"]
# define the tokens as variables
unknownToken, idsym, assignsym, leftbrace, rightbrace,\
varsym, semicolon, whilesym, leftbracket, rightbracket,\
printsym, ifsym, equals, notequals, lessthan, greaterthan,\
number, plus, minus, endfile = range(0, len(tokenNames))
#===============================================================================
class symbol:
#===============================================================================
name = None # String representation
token = None; # Corresponding token
address = 0; # For variables, their runtime address
value = None # on defined for numbers
def __init__(self, name, token, value = 0):
self.name = name
self.token = token
self.address = 0 # for identifiers, their address
self.value = value # for numbers, their value
symtbl = {}; # The Symbol Table, a dictionary of symbols indexed by name
#======================================================================
# GLOBALS for output of Lexical Analyser
# Set by each call to GeToken()
token = None; # A symbol
line = "\n" # the complex source file as a string
charIndex = 0 # the position in the source
linenumber= 0 # The current number
EOF = chr(0)
#======================================================================
# Run Time Code Generation Variables
varptr = 500 # Arbitrary base address of memory for variables
codeptr = 10 # Address to output next instruction (for code)
#===============================================================================
# Symbol Table Management Routines
#===============================================================================
#===============================================================================
def addToSymTbl (name, token):
#===============================================================================
symtbl[name] = symbol(name, token) # Add a new symbol to the dictionary
return symtbl[name]
#===============================================================================
def lookup (thisName):
#===============================================================================
"# Find a given identifier in the Symbol Table, Return the symtbl entry"
if symtbl.has_key(thisName): # thisName has been seen before
return symtbl[thisName] # return the symtbl entry
else: return None
#===============================================================================
def initSymTbl():
#===============================================================================
"# Initialise Symbol Table, and preload reserved words"
addToSymTbl('var', varsym) # VAR
addToSymTbl('while', whilesym) # WHILE
addToSymTbl('print', printsym) # PRINT
addToSymTbl('if', ifsym) # IF
# Now add symbols - NB only single character symbols are here
# multicharacter one like ">=" are still to do
addToSymTbl( '=', assignsym)
addToSymTbl( '#', notequals)
addToSymTbl( '<', lessthan)
addToSymTbl( '>', greaterthan)
addToSymTbl( '{', leftbrace )
addToSymTbl( '}', rightbrace)
addToSymTbl( '(', leftbracket)
addToSymTbl( ')', rightbracket)
addToSymTbl( '+', plus )
addToSymTbl( '-', minus)
addToSymTbl( ';', semicolon)
addToSymTbl( EOF, endfile)
#===============================================================================
# Scanner Diagnostics
#===============================================================================
def printToken(tok):
#===============================================================================
" - display the specified token."
if tok.token == idsym:
print "Token = %10s, %-10s adr = %3d" %\
(tokenNames[tok.token], tok.name, tok.address)
elif tok.token == number:
print "Token = %10s %d" % (tokenNames[tok.token], tok.value)
else:
print "Token = %10s" % tokenNames[tok.token]
#==============================?=================================================
def dumpSymTbl():
#===============================================================================
""" Dump all the tokens in the symboltable """
print(" *** Symbol Table ***")
for name in symtbl.keys(): # keys is a list of the names (printable form of tokens)
tok = symtbl[name]
if tok.token == idsym:
printToken(tok)
#===============================================================================
def getch():
#===============================================================================
global line
global charIndex
global linenumber
while True:
if charIndex < len(line): # See if used up current line
ch = line[charIndex] # if not, get character
charIndex = charIndex+1 # & move pointer for next time
else:
# line = f.readline()
# if line == "": line = EOF
print "--> ",
line = raw_input() +"\n" # read new line, adding \n so it's like f.readline()
charIndex = 0 # & reset character pointer
linenumber = linenumber + 1
continue
if ch == "\n":
ch = " " # A newline is a token separator
if ch == '?':
dumpSymTbl()
continue
return ch
#===============================================================================
def ungetch():
#===============================================================================
""" Unget the next character peeked at when building variables, numbers
and when distinguishing between >= and > ...
"""
global charIndex;
charIndex = charIndex-1;
#===============================================================================
def getoken():
#===============================================================================
""" GETOKEN - Put next token into the global TOKEN """
global token
ch = getch() # skip whitespace
while ch in ["\t", " ", "\n"]:
ch = getch()
# If ch is alphabetic then this is start of reserved word or an identifier
if ch.isalpha(): # Letter therefore it's either identifier or reserved word
name = ""
while ch.isalpha() or ch.isdigit() or ch == "_":
name = name + ch
ch = getch()
ungetch() # let terminator be used next time
token = lookup(name) # See if token's known
if token is None: # if not
token = addToSymTbl(name, idsym) # add as 'idsym'-IDENTIFIER
return # we've set token.token to either id or tokentype of reserved word
#---------------------------------------------------------------------
# If it's numeric return TOKEN=number & token.value = binary value
elif ch.isdigit():
# In the real version, build number and don't forget to end with ungetch()
token = symbol(ch, number, value = int(ch)) # simplistic SINGLE DIGIT Ascii to Binary
return
#---------------------------------------------------------------------
# Single character tokens
elif ch in ["=", "#", "<", ">", "{", "}", "(", ")", "+" , "-" , ";", EOF]:
token = lookup(ch) # preloaded with appropriate token
else:
print "Unknown character -->%s<- decimal %d" % (ch,ord(ch))
sys.exit(1) # Abort Compilation
#======================================================================
# THE GRAMMAR
# <program> ::= { <id> ; <vars > <stmtlist> }
# <vars> ::= var { <id> ; } % DECLARATIONS
# <stmtlist> ::= <stmt> { ; <stmt> }
# <stmt> ::= print <id>
# <id> = <expr>
# <expr> ::= <factor> { (+ | -) <factor> } % No precedence
# <factor> ::= ID | Number
#======================================================================
# Centralised Parser Error Message handler
#======================================================================
#===============================================================================
def error (msg):
#===============================================================================
print line
print "-" * charIndex,"^"
print("Error on %d - %s\n" % (number, msg))
printToken(token)
print("\n")
#===============================================================================
def emit (memadr, opcode, parameter):
#===============================================================================
"""EMIT CODE - Emit a of code with a Parameter
if first arg is zero - (the memory address), use and incr CODEPTR"""
global codeptr
if (memadr == 0):
memadr = codeptr
codeptr = codeptr+1
print "%6d %-8s %-7d" % (memadr, opcode, parameter)
#======================================================================
# VARIABLE DECLARATIONS
# <vars> ::= V { <id> ; }
#===============================================================================
def vars() :
#===============================================================================
global varptr;
getoken(); #skip VARSYM - already been recognised
while (token.token == idsym):
if token.address != 0:
print("%c already declared\n", token.name);
else:
symtbl[token.name].address = varptr;
varptr = varptr +1
getoken(); #skip past identifier
if token.token == semicolon: getoken() #skip ;
else: error("semicolon expected in declaration")
#======================================================================
# STMTLIST
# <stmtlist> ::= <stmt> { ; <stmt> }
#===============================================================================
def stmtList():
#===============================================================================
stmt()
while (token.token == semicolon):
getoken() #skip ;
stmt()
#======================================================================
# STMT
#===============================================================================
def stmt():
#===============================================================================
""" <stmt> ::= print <expression> | <id> = <expression>
"""
global codeptr
thisStmtAdr = codeptr # Jump DEMO - not part of Stmt
if token.token == printsym:
printStmt()
elif token.token == idsym:
assignStmt()
else:
error("Expected start of a statement")
emit (0, "jumpDemo-to start of statement: jump", thisStmtAdr) # Jump DEMO
#===============================================================================
def printStmt():
#===============================================================================
""" <printStmt> ::= print <expression>"""
getoken() # skip "print"
expression() # on return, expr result (at runtime) will be in ACC
emit(0, "output", 0) # Memory address 0 is the ACC
#===============================================================================
def assignStmt():
#===============================================================================
"""
<id> = <expression>
"""
whichidentifier = token # Remember which ID on Left
getoken() # Get token after identifier
if token.token == assignsym:
getoken()
else:
error("Expected = in assignment statement")
expression()
# Save result into LHS runtime address
#===============================================================================
def expression():
#===============================================================================
"""
Leaves result in ACC at runtime
Use addresses 999 & 998 as Temporary variables
<expression> ::= <factor> { (+ | -) <factor> }
"""
factor()
while token.token == plus or token.token == minus:
op = token # remember +/-
getoken() # skip past +/-
emit(0, "store", 999) # Save current result
factor() # Evaluate next factor
if op.token == plus:
emit(0, "add", 999)
else: # Subtract - have to swap operand order
emit(0, "store", 998)
emit(0, "load" , 999)
emit(0, "subtract", 998) # Leaves result in Acc
#===============================================================================
def factor():
#===============================================================================
"""
# FACTOR() - leaves result in ACC at runtime
<factor> ::= identifier | number
"""
if token.token == idsym:
emit(0, "load", token.address)
getoken()
elif token.token == number:
emit(0, "loadv", token.value)
getoken()
else:
error("Start of Factor expected")
#===============================================================================
def program():
#===============================================================================
""" # PROGRAM - Start production of the grammar
# <program> ::= { <id> ; <vars > <stmtlist> }
"""
if token.token == leftbrace: getoken()
else: error(" { expected")
if token.token == idsym: getoken()
else: error("Program name expected")
if token.token == semicolon: getoken()
else: error("Semicolon expected")
if token.token == varsym : vars()
stmtList()
if token.token == rightbrace:
print("\n*** Compilation finished ***\n")
else: error(" } expected")
# Compiler main function
#======================================================================
def main():
#======================================================================
global line
global srcfile
global charIndex
initSymTbl()
# srcfile = open('tiny.txt', 'r')
# line = srcfile.read() # readline
line = """{ G;
var a; b; c;
print a+10;\n""" # a+1
# line = """{ G;
# var a; b; c;
# print a+b-c+8-b-9;\n""" # a+b-c+8-b-9
charIndex = 0
debugScanner = False
if debugScanner: # Scanner Test Routine - Read a line and display the tokens
getoken()
while token.token is not None: # Skeleton for testing Scanner
printToken(token)
getoken()
sys.exit(1)
else:
getoken() # Parse Program according to the grammar
program() # Call start non-terminal handler
#===============================================================================
# Main Compiler starts here
#===============================================================================
print "Microcompiler.py v0.2"
main()
getoken()
#=======================================================================
# *** That's it folks - written by Giovanni Moretti - April 27, 2011 ***
#=======================================================================
| [
[
8,
0,
0.0193,
0.0273,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0364,
0.0023,
0,
0.66,
0.0294,
509,
0,
1,
0,
0,
509,
0,
0
],
[
14,
0,
0.0545,
0.0114,
0,
0.6... | [
"\"\"\" Giovanni's MicroCompiler Demo\n\n<program> ::= { <id> ; <vars > <stmtlist> }\n<vars> ::= V { <id> ; } % DECLARATIONS\n\n<stmtlist> ::= <stmt> { ; <stmt> }\n<stmt> ::= P <id> | <id> = <expr>",
"import sys",
"tokenNames =\\\n [ \"unkno... |
""" Giovanni's MicroCompiler Demo
<program> ::= { <id> ; <vars > <stmtlist> }
<vars> ::= V { <id> ; } % DECLARATIONS
<stmtlist> ::= <stmt> { ; <stmt> }
<stmt> ::= P <id> | <id> = <expr>
<expr> ::= <factor> { (+ | -) <factor> } % No precedence
<factor> ::= (+|-) ID | Number
"""
import sys
import shlex
#===============================================================================
# # Lexical Analyser - the "Scanner" - Define the TokenTypes
#===============================================================================
tokenNames =\
[ "unknownToken", "idsym", "assignsym", "leftbrace", "rightbrace",
"varsym", "semicolon", "whilesym", "leftbracket", "rightbracket",
"printsym", "ifsym", "elsesym", "equals", "notequals", "lessthan", "greaterthan",
"readch", "readint", "writech", "writeint",
"number", "plus", "minus", "mpy", "div", "jumpne", "jumpeq","lessthanequal","greaterthanequal","ex","remainder", "endfile"]
# define the tokens as variables
unknownToken, idsym, assignsym, leftbrace, rightbrace,\
varsym, semicolon, whilesym, leftbracket, rightbracket,\
printsym, ifsym, elsesym, equals, notequals, lessthan, greaterthan,\
readch, readint, writech, writeint,\
number, plus, minus, mpy, div, jumpne, jumpeq, lessthanequal, greaterthanequal,ex,remainder, endfile = range(0, len(tokenNames))
#===============================================================================
class symbol:
#===============================================================================
name = None # String representation
token = None; # Corresponding token
address = 0; # For variables, their runtime address
value = None # on defined for numbers
def __init__(self, name, token, value = 0):
self.name = name
self.token = token
self.address = 0 # for identifiers, their address
self.value = value # for numbers, their value
symtbl = {}; # The Symbol Table, a dictionary of symbols indexed by name
#======================================================================
# GLOBALS for output of Lexical Analyser
# Set by each call to GeToken()
token = None; # A symbol
line = "\n" # the complex source file as a string
charIndex = 0 # the position in the source
linenumber= 0 # The current number
EOF = chr(0)
#======================================================================
# Run Time Code Generation Variables
varptr = 500 # Arbitrary base address of memory for variables
codeptr = 10 # Address to output next instruction (for code)
#===============================================================================
# Symbol Table Management Routines
#===============================================================================
#===============================================================================
def addToSymTbl (name, token):
#===============================================================================
symtbl[name] = symbol(name, token) # Add a new symbol to the dictionary
return symtbl[name]
#===============================================================================
def lookup (thisName):
#===============================================================================
"# Find a given identifier in the Symbol Table, Return the symtbl entry"
if symtbl.has_key(thisName): # thisName has been seen before
return symtbl[thisName] # return the symtbl entry
else: return None
#===============================================================================
def initSymTbl():
#===============================================================================
"# Initialise Symbol Table, and preload reserved words"
addToSymTbl('var', varsym) # VAR
addToSymTbl('while', whilesym) # WHILE
addToSymTbl('for', whilesym) # WHILE
addToSymTbl('print', printsym) # PRINT
addToSymTbl('if', ifsym) # IF
addToSymTbl('else', elsesym) # ELSE
addToSymTbl('readint', readint) #READINT
addToSymTbl('writeint', writeint) #READINT
addToSymTbl('readch', readch) #READINT
addToSymTbl('writech', writech) #READINT
# Now add symbols - NB only single character symbols are here
# multicharacter one like ">=" are still to do
addToSymTbl( '=', assignsym)
addToSymTbl( '#', notequals)
addToSymTbl( '<', lessthan) #jumplt
addToSymTbl( '>', greaterthan) #jumpgt
addToSymTbl( '{', leftbrace )
addToSymTbl( '}', rightbrace)
addToSymTbl( '(', leftbracket)
addToSymTbl( ')', rightbracket)
addToSymTbl( '+', plus )
addToSymTbl( '-', minus)
addToSymTbl( '*', mpy)
addToSymTbl( '/', div)
addToSymTbl( ';', semicolon)
addToSymTbl( '!', ex)
addToSymTbl( '%', remainder)
addToSymTbl( EOF, endfile)
#multicharacter one like ">=" are still to do
addToSymTbl( '==', jumpeq)
addToSymTbl( '!=', jumpne)
addToSymTbl( '<=', lessthanequal) #jumplt
addToSymTbl( '>=', greaterthanequal) #jumpgt
#===============================================================================
# Scanner Diagnostics
#===============================================================================
def printToken(tok):
#===============================================================================
" - display the specified token."
if tok.token == idsym:
print "Token = %10s, %-10s adr = %3d" %\
(tokenNames[tok.token], tok.name, tok.address)
elif tok.token == number:
print "Token = %10s %d" % (tokenNames[tok.token], tok.value)
else:
print "Token = %10s" % tokenNames[tok.token]
#==============================?=================================================
def dumpSymTbl():
#===============================================================================
""" Dump all the tokens in the symboltable """
print(" *** Symbol Table ***")
for name in symtbl.keys(): # keys is a list of the names (printable form of tokens)
tok = symtbl[name]
if tok.token == idsym:
printToken(tok)
#===============================================================================
def getch():
#===============================================================================
global line
global charIndex
global linenumber
while True:
if charIndex < len(line): # See if used up current line
ch = line[charIndex] # if not, get character
charIndex = charIndex+1 # & move pointer for next time
else:
#line = srcfile.readline()
if line == "": line = EOF
#print "--> ",
line = raw_input() +"\n" # read new line, adding \n so it's like f.readline()
charIndex = 0 # & reset character pointer
linenumber = linenumber + 1
continue
if ch == "\n":
ch = " " # A newline is a token separator
if ch == "?":
dumpSymTbl()
continue
if ch == "#":
print "#Comment Found"
srcfile.read()
print "#Read next line"
return ch
#===============================================================================
def ungetch():
#===============================================================================
""" Unget the next character peeked at when building variables, numbers
and when distinguishing between >= and > ...
"""
global charIndex;
charIndex = charIndex-1;
#===============================================================================
def getoken():
#===============================================================================
""" GETOKEN - Put next token into the global TOKEN """
global token
ch = getch() # skip whitespace
while ch in ["\t", " ", "\n", "#"]:
ch = getch()
# If ch is alphabetic then this is start of reserved word or an identifier
if ch.isalpha(): # Letter therefore it's either identifier or reserved word
name = ""
while ch.isalpha() or ch.isdigit() or ch == "_":
name = name + ch
ch = getch()
ungetch() # let terminator be used next time
token = lookup(name) # See if token's known
if token is None: # if not
token = addToSymTbl(name, idsym) # add as 'idsym'-IDENTIFIER
return # we've set token.token to either id or tokentype of reserved word
#---------------------------------------------------------------------
# If it's numeric return TOKEN=number & token.value = binary value
elif ch.isdigit():
# In the real version, build number and don't forget to end with ungetch()
token = symbol(ch, number, value = int(ch)) # simplistic SINGLE DIGIT Ascii to Binary
return
#---------------------------------------------------------------------
# Single character tokens
elif ch in ["#", "{", "}", "(", ")", "+" , "-", "*", "/", ";","%", EOF]:
token = lookup(ch) # preloaded with appropriate token
elif ch in ["!"]:
ch = getch()
char = "!"
nEqual = "!="
if ch == "=":
char = nEqual
ch = getch()
else:
token = lookup(ch)
ungetch()
token = lookup(char)
if token is None:
token = addToSymTbl(char, idsym)
return
elif ch in ["="]:
ch = getch()
char = "="
Equal = "=="
if ch == "=":
char = Equal
ch = getch()
else:
token = lookup(ch)
ungetch()
token = lookup(char)
if token is None:
token = addToSymTbl(char, idsym)
return
elif ch in ["<"]:
ch = getch()
char = "<"
lessthanEqual = "<="
if ch == "=":
char = lessthanEqual
ch = getch()
else:
token = lookup(ch)
ungetch()
token = lookup(char)
if token is None:
token = addToSymTbl(char, idsym)
return
elif ch in [">"]:
ch = getch()
char = ">"
greatthanEqual = ">="
if ch == "=":
char = greatthanEqual
ch = getch()
else:
token = lookup(ch)
ungetch()
token = lookup(char)
if token is None:
token = addToSymTbl(char, idsym)
return
else:
print "Unknown character -->%s<- decimal %d" % (ch,ord(ch))
sys.exit(1) # Abort Compilation
#======================================================================
# THE GRAMMAR
# <program> ::= { <id> ; <vars > <stmtlist> }
# <vars> ::= var { <id> ; } % DECLARATIONS
# <array> ::= [<expr>]
# <stmtlist> ::= <stmt> { ; <stmt> }
# <stmt> ::= print <id>
# <id> = <expr>
# <expr> ::= <factor> { (+ | -) <factor> } % No precedence
# <factor> ::= [+/-] ID | Number
#======================================================================
# Centralised Parser Error Message handler
#======================================================================
#===============================================================================
def error (msg):
#===============================================================================
print line
print "-" * charIndex,"^"
print("Error on %d - %s\n" % (number, msg))
printToken(token)
print("\n")
#===============================================================================
def emit (memadr, opcode, parameter):
#===============================================================================
"""EMIT CODE - Emit a of code with a Parameter
if first arg is zero - (the memory address), use and incr CODEPTR"""
global codeptr
if (memadr == 0):
memadr = codeptr
codeptr = codeptr+1
print "%6d %-8s %-7s" % (memadr, opcode, parameter)
#======================================================================
# VARIABLE DECLARATIONS
# <vars> ::= V { <id> ; }
#===============================================================================
def vars() :
#===============================================================================
global varptr;
getoken(); #skip VARSYM - already been recognised
while (token.token == idsym):
if token.address != 0:
print("%c already declared\n", token.name);
else:
symtbl[token.name].address = varptr;
varptr = varptr +1
getoken(); #skip past identifier
if token.token == semicolon: getoken() #skip ;
else: error("semicolon expected in declaration")
#======================================================================
# STMTLIST
# <stmtlist> ::= <stmt> { ; <stmt> }
#===============================================================================
def stmtList():
#===============================================================================
stmt()
while (token.token == semicolon):
getoken() #skip ;
stmt()
#======================================================================
# STMT
#===============================================================================
def stmt():
#===============================================================================
""" <stmt> ::= print <expression> | <id> = <expression> | if <expression> | while <expression>
"""
global codeptr
# thisStmtAdr = codeptr # Jump DEMO - not part of Stmt
if token.token == printsym:
printStmt()
elif token.token == idsym:
assignStmt()
elif token.token == assignsym:
getoken()
elif token.token == ifsym:
ifStmt()
elif token.token == elsesym:
elseStmt()
elif token.token == whilesym:
whileStmt()
elif token.token == readint:
readIntStmt()
elif token.token == readch:
readChStmt()
elif token.token == writeint:
writeIntStmt()
elif token.token == writech:
writeChStmt()
elif token.token == rightbrace:
print("\n#*** Compilation finished ***\n")
else:
error("Expected start of a statement")
# emit (0, "return", thisStmtAdr) # Jump DEMO
#===============================================================================
def printStmt():
#===============================================================================
""" <printStmt> ::= print <expression>"""
getoken() # skip "print"
expression() # on return, expr result (at runtime) will be in ACC
emit(0, "writeint", 0) # Memory address 0 is the ACC
if token.token == rightbrace:
print("#\n*** Compilation finished ***\n")
#===============================================================================
def assignStmt():
#===============================================================================
"""
<id> = <expression>
"""
whichidentifier = token # Remember which ID on Left
getoken() # Get token after identifier
if token.token == notequals: # skip # then read next line
srcfile.read()
getoken()
elif token.token == assignsym: #if the next token is =
expression()
elif token.token == idsym: factor()
elif token.token == jumpeq: print("#")
elif token.token == jumpne: print("#")
elif token.token == lessthanequal: print("")
elif token.token == greaterthanequal: print("")
else:
error("Expected = in assignment statement")
expression()
# Save result into LHS runtime address
#===============================================================================
def ifStmt():
#if-then-else
#===============================================================================
""" <ifStmt> ::= if <expression>"""
getoken() # skip "if"
emit(0, "compare",60)
expression()
stmt()
emit(0, "return",0)
#===============================================================================
def elseStmt():
#if-then-else
#===============================================================================
""" <elseStmt> ::= else <expression>"""
getoken()
emit(0, "store", 888)
stmt()
#===============================================================================
def whileStmt():
#===============================================================================
""" <whileStmt> ::= while (condition)statement"""
getoken() # skip "if"
emit(0, "compare",50)
expression()
stmt()
emit(0, "increment", 1)
emit(0, "jumpi", 14)
#===============================================================================
def readIntStmt():
#===============================================================================
getoken()
expression() # skip "if"
emit(0, "readint",999)
#===============================================================================
def readChStmt():
#===============================================================================
getoken() # skip "if"
emit(0, "readch",11)
#===============================================================================
def writeIntStmt():
#===============================================================================
getoken() # skip "if"
expression()
emit(0, "writeint",50)
#===============================================================================
def writeChStmt():
#===============================================================================
getoken() # skip "if"
emit(0, "writech",51)
#===============================================================================
def expression():
#===============================================================================
"""
Leaves result in ACC at runtime
Use addresses 999 & 998 as Temporary variables
<expression> ::= <factor> { (+ | - | * | /) <factor> }
"""
factor()
while token.token == plus or token.token == minus or token.token == mpy or token.token == div or token.token == lessthan or token.token == greaterthan or token.token == jumpeq or token.token == jumpne or token.token == lessthanequal or token.token == greaterthanequal:
op = token # remember +/-
getoken() # skip past +/-
emit(0, "store", 999) # Save current result
factor() # Evaluate next factor
#working
if op.token == plus: #+
emit(0, "loadv", 999)
emit(0, "add", 999)
emit(0, "store", 999)
elif op.token == minus: # - Subtract - have to swap operand order
emit(0, "store", 998)
emit(0, "load" , 999)
emit(0, "subtract", 998) # Leaves result in Acc
emit(0, "store", 880)
elif op.token == mpy: #*
emit(0, "store", 998)
emit(0, "load", 999)
emit(0, "mpy", 998)
emit(0, "store", 881)
elif op.token == div: #/
emit(0, "store", 998)
emit(0, "load", 999)
emit(0, "div", 998)
emit(0, "store", 882)
elif op.token == remainder: #%
emit(0, "store", 998)
emit(0, "load", 999)
emit(0, "mod", 998)
emit(0, "store", 883)
elif op.token == jumpeq: #==
emit(0, "store", 998)
emit(0, "load", 999)
emit(0, "jumpeq", 56)
elif op.token == jumpne: #!=
emit(0, "store", 998)
emit(0, "compare", 999)
emit(0, "jumpne", 82)
emit(0, "loadv", 0)
emit(0, "store", 884)
elif op.token == lessthanequal: #<=
emit(0, "store", 998)
emit(0, "compare", 999)
emit(0, "jumplt", 82)
emit(0, "loadv", 0)
emit(0, "store", 885)
elif op.token == lessthanequal: #<=
emit(0, "store", 998)
emit(0, "compare", 999)
emit(0, "jumpgt", 82)
emit(0, "loadv", 0)
emit(0, "store", 886)
#===============================================================================
def factor():
#===============================================================================
"""
# FACTOR() - leaves result in ACC at runtime
<factor> ::= (+|-) identifier | number
"""
#Numbers
if token.token == idsym:
emit(0, "load", token.address)
getoken()
elif token.token == number:
emit(0, "loadv", token.value)
getoken()
elif token.token == assignsym:getoken()
elif token.token == jumpeq:
print("#==")
elif token.token == jumpne:
print("#!=")
elif token.token == lessthanequal:
print("#<=")
elif token.token == greaterthanequal:
print("#<=")
elif token.token == semicolon: getoken()
else: error("Start of Factor expected")
#===============================================================================
def program():
#===============================================================================
""" # PROGRAM - Start production of the grammar
# <program> ::= { <id> ; <vars > <stmtlist> }
"""
if token.token == leftbrace: getoken()
else: error(" { expected")
if token.token == idsym: getoken()
else: error("Program name expected")
if token.token == semicolon: getoken()
else: error("Semicolon expected")
if token.token == varsym : vars()
stmtList()
if token.token == number:
factor()
elif token.token == idsym: factor()
elif token.token == rightbrace:
print("\n")
else: error(" } expected")
# Compiler main function
#======================================================================
def main():
#======================================================================
global line
global srcfile
global outfile
global charIndex
initSymTbl()
srcfile = open('tiny_2.txt', 'r')
line = srcfile.read() # readline
# for line in open('tiny.txt', 'r'):
# if not line.startswith("#"):
# debugScanner = False
charIndex = 0
debugScanner = False
if debugScanner: # Scanner Test Routine - Read a line and display the tokens
getoken()
while token.token is not None: # Skeleton for testing Scanner
printToken(token)
# outfile.write(token)
getoken()
srcfile.close()
sys.exit(1)
else:
getoken() # Parse Program according to the grammar
program() # Call start non-terminal handler
#===============================================================================
# Main Compiler starts here
#===============================================================================
print "#Microcompiler.py v0.2"
emit(0, "load", 0)
main()
#srcfile = open('tiny.txt', 'r')
#lexer = shlex.shlex(srcfile)
#for token in lexer:
# print repr(token)
getoken()
| [
[
8,
0,
0.0122,
0.0173,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.023,
0.0014,
0,
0.66,
0.0233,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.0245,
0.0014,
0,
0.66,... | [
"\"\"\" Giovanni's MicroCompiler Demo\n\n<program> ::= { <id> ; <vars > <stmtlist> }\n<vars> ::= V { <id> ; } % DECLARATIONS\n\n<stmtlist> ::= <stmt> { ; <stmt> }\n<stmt> ::= P <id> | <id> = <expr>",
"import sys",
"import shlex",
"tokenName... |
""" Giovanni's MicroCompiler Demo
<program> ::= { <id> ; <vars > <stmtlist> }
<vars> ::= V { <id> ; } % DECLARATIONS
<stmtlist> ::= <stmt> { ; <stmt> }
<stmt> ::= P <id> | <id> = <expr>
<expr> ::= <factor> { (+ | -) <factor> } % No precedence
<factor> ::= (+|-) ID | Number
"""
import sys
import shlex
#===============================================================================
# # Lexical Analyser - the "Scanner" - Define the TokenTypes
#===============================================================================
tokenNames =\
[ "unknownToken", "idsym", "assignsym", "leftbrace", "rightbrace",
"varsym", "semicolon", "whilesym", "leftbracket", "rightbracket",
"printsym","printmsg", "ifsym", "elsesym", "equals", "notequals", "lessthan", "greaterthan",
"readch", "readint", "writech", "writeint",
"number", "plus", "minus", "mpy", "div", "jumpne", "jumpeq","lessthanequal","greaterthanequal", "endfile"]
# define the tokens as variables
unknownToken, idsym, assignsym, leftbrace, rightbrace,\
varsym, semicolon, whilesym, leftbracket, rightbracket,\
printsym,printmsg, ifsym, elsesym, equals, notequals, lessthan, greaterthan,\
readch, readint, writech, writeint,\
number, plus, minus, mpy, div, jumpne, jumpeq, lessthanequal, greaterthanequal, endfile = range(0, len(tokenNames))
#===============================================================================
class symbol:
#===============================================================================
name = None # String representation
token = None; # Corresponding token
address = 0; # For variables, their runtime address
value = None # on defined for numbers
def __init__(self, name, token, value = 0):
self.name = name
self.token = token
self.address = 0 # for identifiers, their address
self.value = value # for numbers, their value
symtbl = {}; # The Symbol Table, a dictionary of symbols indexed by name
#======================================================================
# GLOBALS for output of Lexical Analyser
# Set by each call to GeToken()
token = None; # A symbol
line = "\n" # the complex source file as a string
charIndex = 0 # the position in the source
linenumber= 0 # The current number
EOF = chr(0)
#======================================================================
# Run Time Code Generation Variables
varptr = 500 # Arbitrary base address of memory for variables
codeptr = 10 # Address to output next instruction (for code)
#===============================================================================
# Symbol Table Management Routines
#===============================================================================
#===============================================================================
def addToSymTbl (name, token):
#===============================================================================
symtbl[name] = symbol(name, token) # Add a new symbol to the dictionary
return symtbl[name]
#===============================================================================
def lookup (thisName):
#===============================================================================
"# Find a given identifier in the Symbol Table, Return the symtbl entry"
if symtbl.has_key(thisName): # thisName has been seen before
return symtbl[thisName] # return the symtbl entry
else: return None
#===============================================================================
def initSymTbl():
#===============================================================================
"# Initialise Symbol Table, and preload reserved words"
addToSymTbl('var', varsym) # VAR
addToSymTbl('while', whilesym) # WHILE
addToSymTbl('for', whilesym) # WHILE
addToSymTbl('print', printsym) # PRINT
addToSymTbl('printmsg', printmsg)
addToSymTbl('if', ifsym) # IF
addToSymTbl('else', elsesym) # ELSE
addToSymTbl('readint', readint) #READINT
addToSymTbl('writeint', writeint) #READINT
addToSymTbl('readch', readch) #READINT
addToSymTbl('writech', writech) #READINT
# Now add symbols - NB only single character symbols are here
# multicharacter one like ">=" are still to do
addToSymTbl( '=', assignsym)
addToSymTbl( '#', notequals)
addToSymTbl( '<', lessthan) #jumplt
addToSymTbl( '>', greaterthan) #jumpgt
addToSymTbl( '{', leftbrace )
addToSymTbl( '}', rightbrace)
addToSymTbl( '(', leftbracket)
addToSymTbl( ')', rightbracket)
addToSymTbl( '+', plus )
addToSymTbl( '-', minus)
addToSymTbl( '*', mpy)
addToSymTbl( '/', div)
addToSymTbl( ';', semicolon)
addToSymTbl( EOF, endfile)
#multicharacter one like ">=" are still to do
addToSymTbl( '==', jumpeq)
addToSymTbl( '!=', jumpne)
addToSymTbl( '<=', lessthanequal) #jumplt
addToSymTbl( '>=', greaterthanequal) #jumpgt
#===============================================================================
# Scanner Diagnostics
#===============================================================================
def printToken(tok):
#===============================================================================
" - display the specified token."
if tok.token == idsym:
print "Token = %10s, %-10s adr = %3d" %\
(tokenNames[tok.token], tok.name, tok.address)
elif tok.token == number:
print "Token = %10s %d" % (tokenNames[tok.token], tok.value)
else:
print "Token = %10s" % tokenNames[tok.token]
#==============================?=================================================
def dumpSymTbl():
#===============================================================================
""" Dump all the tokens in the symboltable """
print(" *** Symbol Table ***")
for name in symtbl.keys(): # keys is a list of the names (printable form of tokens)
tok = symtbl[name]
if tok.token == idsym:
printToken(tok)
#===============================================================================
def getch():
#===============================================================================
global line
global charIndex
global linenumber
while True:
if charIndex < len(line): # See if used up current line
ch = line[charIndex] # if not, get character
charIndex = charIndex+1 # & move pointer for next time
else:
#line = srcfile.readline()
#if line == "": line = EOF
#if line == "#": line = notequals
#print "--> ",
line = raw_input() +"\n" # read new line, adding \n so it's like f.readline()
charIndex = 0 # & reset character pointer
linenumber = linenumber + 1
continue
if ch == "\n":
ch = " " # A newline is a token separator
if ch == "?":
dumpSymTbl()
continue
return ch
#===============================================================================
def ungetch():
#===============================================================================
""" Unget the next character peeked at when building variables, numbers
and when distinguishing between >= and > ...
"""
global charIndex;
charIndex = charIndex-1;
#===============================================================================
def getoken():
#===============================================================================
""" GETOKEN - Put next token into the global TOKEN """
global token
ch = getch() # skip whitespace
while ch in ["\t", " ", "\n", "#"]:
ch = getch()
# If ch is alphabetic then this is start of reserved word or an identifier
if ch.isalpha(): # Letter therefore it's either identifier or reserved word
name = ""
while ch.isalpha() or ch.isdigit() or ch == "_":
name = name + ch
ch = getch()
ungetch() # let terminator be used next time
token = lookup(name) # See if token's known
if token is None: # if not
token = addToSymTbl(name, idsym) # add as 'idsym'-IDENTIFIER
return # we've set token.token to either id or tokentype of reserved word
#---------------------------------------------------------------------
# If it's numeric return TOKEN=number & token.value = binary value
elif ch.isdigit():
# In the real version, build number and don't forget to end with ungetch()
token = symbol(ch, number, value = int(ch)) # simplistic SINGLE DIGIT Ascii to Binary
return
#---------------------------------------------------------------------
# Single character tokens
elif ch in ["=", "#", "<", ">", "{", "}", "(", ")", "+" , "-", "*", "/", ";","!", "==", EOF]:
token = lookup(ch) # preloaded with appropriate token
else:
print "Unknown character -->%s<- decimal %d" % (ch,ord(ch))
sys.exit(1) # Abort Compilation
#======================================================================
# THE GRAMMAR
# <program> ::= { <id> ; <vars > <stmtlist> }
# <vars> ::= var { <id> ; } % DECLARATIONS
# <stmtlist> ::= <stmt> { ; <stmt> }
# <stmt> ::= print <id>
# <id> = <expr>
# <expr> ::= <factor> { (+ | -) <factor> } % No precedence
# <factor> ::= ID | Number
#======================================================================
# Centralised Parser Error Message handler
#======================================================================
#===============================================================================
def error (msg):
#===============================================================================
print line
print "-" * charIndex,"^"
print("Error on %d - %s\n" % (number, msg))
printToken(token)
print("\n")
#===============================================================================
def emit (memadr, opcode, parameter):
#===============================================================================
"""EMIT CODE - Emit a of code with a Parameter
if first arg is zero - (the memory address), use and incr CODEPTR"""
global codeptr
if (memadr == 0):
memadr = codeptr
codeptr = codeptr+1
print "%6d %-8s %-7s" % (memadr, opcode, parameter)
#======================================================================
# VARIABLE DECLARATIONS
# <vars> ::= V { <id> ; }
#===============================================================================
def vars() :
#===============================================================================
global varptr;
getoken(); #skip VARSYM - already been recognised
while (token.token == idsym):
if token.address != 0:
print("%c already declared\n", token.name);
else:
symtbl[token.name].address = varptr;
varptr = varptr +1
getoken(); #skip past identifier
if token.token == semicolon: getoken() #skip ;
else: error("semicolon expected in declaration")
#======================================================================
# STMTLIST
# <stmtlist> ::= <stmt> { ; <stmt> }
#===============================================================================
def stmtList():
#===============================================================================
stmt()
while (token.token == semicolon):
getoken() #skip ;
stmt()
#======================================================================
# STMT
#===============================================================================
def stmt():
#===============================================================================
""" <stmt> ::= print <expression> | <id> = <expression> | if <expression> | while <expression>
"""
global codeptr
# thisStmtAdr = codeptr # Jump DEMO - not part of Stmt
if token.token == printsym:
printStmt()
elif token.token == printmsg:
printMsg()
elif token.token == idsym:
assignStmt()
elif token.token == ifsym:
ifStmt()
elif token.token == elsesym:
elseStmt()
elif token.token == whilesym:
whileStmt()
elif token.token == readint:
readIntStmt()
elif token.token == readch:
readChStmt()
elif token.token == writeint:
writeIntStmt()
elif token.token == writech:
writeChStmt()
else:
error("Expected start of a statement")
# emit (0, "return", thisStmtAdr) # Jump DEMO
#===============================================================================
def printStmt():
#===============================================================================
""" <printStmt> ::= print <expression>"""
getoken() # skip "print"
expression() # on return, expr result (at runtime) will be in ACC
# emit(0, "writeint", 0) # Memory address 0 is the ACC
if token.token == rightbrace:
print("\n*** Compilation finished ***\n")
#===============================================================================
def printMsg():
#===============================================================================
""" <printMsg> ::= printMsg <expression>"""
emit(0, "loadv", 100)
emit(0, "store", 1)
emit(0, "call", 40)
emit(40, "load-Ind", 0)
emit(41, "jumpeq", 45)
emit(42, "writech",150)
emit(43, "increment", 1)
emit(44, "jump", 40)
emit(45, "return", 0)
#===============================================================================
def assignStmt():
#===============================================================================
"""
<id> = <expression>
"""
whichidentifier = token # Remember which ID on Left
getoken() # Get token after identifier
if token.token == assignsym:
getoken()
elif token.token == jumpeq:
getoken()
else:
error("Expected = in assignment statement")
expression()
# Save result into LHS runtime address
#===============================================================================
def ifStmt():
#if-then-else
#===============================================================================
""" <ifStmt> ::= if <expression>"""
getoken() # skip "if"
emit(0, "compare",60)
expression()
stmt()
emit(0, "return",0)
#===============================================================================
def elseStmt():
#if-then-else
#===============================================================================
""" <elseStmt> ::= else <expression>"""
getoken()
emit(0, "store", 888)
stmt()
#===============================================================================
def whileStmt():
#===============================================================================
""" <whileStmt> ::= while (condition)statement"""
getoken() # skip "if"
emit(0, "compare",50)
expression()
stmt()
emit(0, "increment", 1)
emit(0, "jumpi", 14)
#===============================================================================
def readIntStmt():
#===============================================================================
getoken()
expression() # skip "if"
emit(0, "readint",12)
#===============================================================================
def readChStmt():
#===============================================================================
getoken() # skip "if"
emit(0, "readch",11)
#===============================================================================
def writeIntStmt():
#===============================================================================
getoken() # skip "if"
expression()
emit(0, "writeint",50)
return
#===============================================================================
def writeChStmt():
#===============================================================================
getoken() # skip "if"
emit(0, "writech",token.value)
return
#===============================================================================
def expression():
#===============================================================================
"""
Leaves result in ACC at runtime
Use addresses 999 & 998 as Temporary variables
<expression> ::= <factor> { (+ | - | * | /) <factor> }
"""
factor()
while token.token == plus or token.token == minus or token.token == mpy or token.token == div or token.token == lessthan or token.token == greaterthan or token.token == jumpne or token.token == jumpeq:
op = token # remember +/-
getoken() # skip past +/-
emit(0, "store", 999) # Save current result
factor() # Evaluate next factor
#working
if op.token == plus:
emit(0, "loadv", 999)
emit(0, "add", 999)
emit(0, "store", 777)
if op.token == leftbracket:getoken()
elif op.token == minus: # Subtract - have to swap operand order
emit(0, "store", 998)
emit(0, "load" , 999)
emit(0, "subtract", 998) # Leaves result in Acc
emit(0, "store", 6)
elif op.token == mpy:
emit(0, "store", 998)
emit(0, "load", 999)
emit(0, "mpy", 998)
emit(0, "store", 7)
elif op.token == div:
emit(0, "store", 998)
emit(0, "load", 999)
emit(0, "div", 998)
emit(0, "store", 8)
elif op.token == lessthan:
emit(0, "store", 998)
emit(0, "compare", 999)
emit(0, "jumplt", 80)
emit(0, "loadv", 0)
emit(0, "store", 9)
elif op.token == greaterthan:
emit(0, "store", 998)
emit(0, "compare", 999)
emit(0, "jumpgt", 81)
emit(0, "loadv", 0)
emit(0, "store", 10)
#===============================================================================
def factor():
#===============================================================================
"""
# FACTOR() - leaves result in ACC at runtime
<factor> ::= (+|-) identifier | number
"""
#+ (unary)
if token.token == plus:
getoken()
token.value = token.value
#- (unary)
elif token.token == minus:
getoken()
token.value = -token.value
#Numbers
if token.token == idsym:
emit(0, "load", token.address)
getoken()
elif token.token == number:
emit(0, "loadv", token.value)
getoken()
else: error("Start of Factor expected")
#===============================================================================
def program():
#===============================================================================
""" # PROGRAM - Start production of the grammar
# <program> ::= { <id> ; <vars > <stmtlist> }
"""
if token.token == leftbrace: getoken()
else: error(" { expected")
if token.token == idsym: getoken()
else: error("Program name expected")
if token.token == semicolon: getoken()
else: error("Semicolon expected")
if token.token == varsym : vars()
stmtList()
if token.token == printmsg:
getoken()
elif token.token == rightbrace:
print("\n*** Compilation finished ***\n")
else: error(" } expected")
# Compiler main function
#======================================================================
def main():
#======================================================================
global line
global srcfile
global outfile
global charIndex
initSymTbl()
srcfile = open('writeOutput.txt', 'r')
line = srcfile.read() # readline
# for line in open('tiny.txt', 'r'):
# if not line.startswith("#"):
# debugScanner = False
charIndex = 0
debugScanner = False
if debugScanner: # Scanner Test Routine - Read a line and display the tokens
getoken()
while token.token is not None: # Skeleton for testing Scanner
printToken(token)
getoken()
sys.exit(1)
else:
getoken() # Parse Program according to the grammar
program() # Call start non-terminal handler
#===============================================================================
# Main Compiler starts here
#===============================================================================
#outfile = open('writeOutput.obj', 'w')
print "#Microcompiler.py v0.2"
emit(0, "load", 0)
emit(100, "constant", "'A'")
emit(101, "constant", "'P'")
emit(102, "constant", "'P'")
emit(103, "constant", "'L'")
emit(104, "constant", "'E'")
main()
#srcfile = open('writeOutput_unarry_plue_minus.txt', 'r')
#lexer = shlex.shlex(srcfile)
#for token in lexer:
# print repr(token)
#getoken()
| [
[
8,
0,
0.0139,
0.0196,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0261,
0.0016,
0,
0.66,
0.0208,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.0277,
0.0016,
0,
0.66... | [
"\"\"\" Giovanni's MicroCompiler Demo\n\n<program> ::= { <id> ; <vars > <stmtlist> }\n<vars> ::= V { <id> ; } % DECLARATIONS\n\n<stmtlist> ::= <stmt> { ; <stmt> }\n<stmt> ::= P <id> | <id> = <expr>",
"import sys",
"import shlex",
"tokenName... |
""" Giovanni's MicroCompiler Demo
<program> ::= { <id> ; <vars > <stmtlist> }
<vars> ::= V { <id> ; } % DECLARATIONS
<stmtlist> ::= <stmt> { ; <stmt> }
<stmt> ::= P <id> | <id> = <expr>
<expr> ::= <factor> { (+ | -) <factor> } % No precedence
<factor> ::= (+|-) ID | Number
"""
import sys
import shlex
#===============================================================================
# # Lexical Analyser - the "Scanner" - Define the TokenTypes
#===============================================================================
tokenNames =\
[ "unknownToken", "idsym", "assignsym", "leftbrace", "rightbrace",
"varsym", "semicolon", "whilesym", "leftbracket", "rightbracket",
"printsym", "ifsym", "elsesym", "equals", "notequals", "lessthan", "greaterthan",
"readch", "readint", "writech", "writeint",
"number", "plus", "minus", "mpy", "div", "jumpne", "jumpeq","lessthanequal","greaterthanequal", "endfile"]
# define the tokens as variables
unknownToken, idsym, assignsym, leftbrace, rightbrace,\
varsym, semicolon, whilesym, leftbracket, rightbracket,\
printsym, ifsym, elsesym, equals, notequals, lessthan, greaterthan,\
readch, readint, writech, writeint,\
number, plus, minus, mpy, div, jumpne, jumpeq, lessthanequal, greaterthanequal, endfile = range(0, len(tokenNames))
#===============================================================================
class symbol:
#===============================================================================
name = None # String representation
token = None; # Corresponding token
address = 0; # For variables, their runtime address
value = None # on defined for numbers
def __init__(self, name, token, value = 0):
self.name = name
self.token = token
self.address = 0 # for identifiers, their address
self.value = value # for numbers, their value
symtbl = {}; # The Symbol Table, a dictionary of symbols indexed by name
#======================================================================
# GLOBALS for output of Lexical Analyser
# Set by each call to GeToken()
token = None; # A symbol
line = "\n" # the complex source file as a string
charIndex = 0 # the position in the source
linenumber= 0 # The current number
EOF = chr(0)
#======================================================================
# Run Time Code Generation Variables
varptr = 500 # Arbitrary base address of memory for variables
codeptr = 10 # Address to output next instruction (for code)
#===============================================================================
# Symbol Table Management Routines
#===============================================================================
#===============================================================================
def addToSymTbl (name, token):
#===============================================================================
symtbl[name] = symbol(name, token) # Add a new symbol to the dictionary
return symtbl[name]
#===============================================================================
def lookup (thisName):
#===============================================================================
"# Find a given identifier in the Symbol Table, Return the symtbl entry"
if symtbl.has_key(thisName): # thisName has been seen before
return symtbl[thisName] # return the symtbl entry
else: return None
#===============================================================================
def initSymTbl():
#===============================================================================
"# Initialise Symbol Table, and preload reserved words"
addToSymTbl('var', varsym) # VAR
addToSymTbl('while', whilesym) # WHILE
addToSymTbl('for', whilesym) # WHILE
addToSymTbl('print', printsym) # PRINT
addToSymTbl('if', ifsym) # IF
addToSymTbl('else', elsesym) # ELSE
addToSymTbl('readint', readint) #READINT
addToSymTbl('writeint', writeint) #READINT
addToSymTbl('readch', readch) #READINT
addToSymTbl('writech', writech) #READINT
# Now add symbols - NB only single character symbols are here
# multicharacter one like ">=" are still to do
addToSymTbl( '=', assignsym)
addToSymTbl( '#', notequals)
addToSymTbl( '<', lessthan) #jumplt
addToSymTbl( '>', greaterthan) #jumpgt
addToSymTbl( '{', leftbrace )
addToSymTbl( '}', rightbrace)
addToSymTbl( '(', leftbracket)
addToSymTbl( ')', rightbracket)
addToSymTbl( '+', plus )
addToSymTbl( '-', minus)
addToSymTbl( '*', mpy)
addToSymTbl( '/', div)
addToSymTbl( ';', semicolon)
addToSymTbl( EOF, endfile)
#multicharacter one like ">=" are still to do
addToSymTbl( '==', jumpeq)
addToSymTbl( '!=', jumpne)
addToSymTbl( '<=', lessthanequal) #jumplt
addToSymTbl( '>=', greaterthanequal) #jumpgt
#===============================================================================
# Scanner Diagnostics
#===============================================================================
def printToken(tok):
#===============================================================================
" - display the specified token."
if tok.token == idsym:
print "Token = %10s, %-10s adr = %3d" %\
(tokenNames[tok.token], tok.name, tok.address)
elif tok.token == number:
print "Token = %10s %d" % (tokenNames[tok.token], tok.value)
else:
print "Token = %10s" % tokenNames[tok.token]
#==============================?=================================================
def dumpSymTbl():
#===============================================================================
""" Dump all the tokens in the symboltable """
print(" *** Symbol Table ***")
for name in symtbl.keys(): # keys is a list of the names (printable form of tokens)
tok = symtbl[name]
if tok.token == idsym:
printToken(tok)
#===============================================================================
def getch():
#===============================================================================
global line
global charIndex
global linenumber
while True:
if charIndex < len(line): # See if used up current line
ch = line[charIndex] # if not, get character
charIndex = charIndex+1 # & move pointer for next time
else:
#line = srcfile.readline()
if line == "": line = EOF
print "--> ",
line = raw_input() +"\n" # read new line, adding \n so it's like f.readline()
charIndex = 0 # & reset character pointer
linenumber = linenumber + 1
continue
if ch == "\n":
ch = " " # A newline is a token separator
if ch == "?":
dumpSymTbl()
continue
if ch == "#":
print "#Comment Found"
srcfile.read()
print "#Read next line"
return ch
#===============================================================================
def ungetch():
#===============================================================================
""" Unget the next character peeked at when building variables, numbers
and when distinguishing between >= and > ...
"""
global charIndex;
charIndex = charIndex-1;
#===============================================================================
def getoken():
#===============================================================================
""" GETOKEN - Put next token into the global TOKEN """
global token
ch = getch() # skip whitespace
while ch in ["\t", " ", "\n", "#"]:
ch = getch()
# If ch is alphabetic then this is start of reserved word or an identifier
if ch.isalpha(): # Letter therefore it's either identifier or reserved word
name = ""
while ch.isalpha() or ch.isdigit() or ch == "_":
name = name + ch
ch = getch()
ungetch() # let terminator be used next time
token = lookup(name) # See if token's known
if token is None: # if not
token = addToSymTbl(name, idsym) # add as 'idsym'-IDENTIFIER
return # we've set token.token to either id or tokentype of reserved word
#---------------------------------------------------------------------
# If it's numeric return TOKEN=number & token.value = binary value
elif ch.isdigit():
# In the real version, build number and don't forget to end with ungetch()
token = symbol(ch, number, value = int(ch)) # simplistic SINGLE DIGIT Ascii to Binary
return
#---------------------------------------------------------------------
# Single character tokens
elif ch in ["=", "#", "<", ">", "{", "}", "(", ")", "+" , "-", "*", "/", ";","!", "==", EOF]:
token = lookup(ch) # preloaded with appropriate token
else:
print "Unknown character -->%s<- decimal %d" % (ch,ord(ch))
sys.exit(1) # Abort Compilation
#======================================================================
# THE GRAMMAR
# <program> ::= { <id> ; <vars > <stmtlist> }
# <vars> ::= var { <id> ; } % DECLARATIONS
# <array> ::= [<expr>]
# <stmtlist> ::= <stmt> { ; <stmt> }
# <stmt> ::= print <id>
# <id> = <expr>
# <expr> ::= <factor> { (+ | -) <factor> } % No precedence
# <factor> ::= [+/-] ID | Number
#======================================================================
# Centralised Parser Error Message handler
#======================================================================
#===============================================================================
def error (msg):
#===============================================================================
print line
print "-" * charIndex,"^"
print("Error on %d - %s\n" % (number, msg))
printToken(token)
print("\n")
#===============================================================================
def emit (memadr, opcode, parameter):
#===============================================================================
"""EMIT CODE - Emit a of code with a Parameter
if first arg is zero - (the memory address), use and incr CODEPTR"""
global codeptr
if (memadr == 0):
memadr = codeptr
codeptr = codeptr+1
print "%6d %-8s %-7s" % (memadr, opcode, parameter)
#======================================================================
# VARIABLE DECLARATIONS
# <vars> ::= V { <id> ; }
#===============================================================================
def vars() :
#===============================================================================
global varptr;
getoken(); #skip VARSYM - already been recognised
while (token.token == idsym):
if token.address != 0:
print("%c already declared\n", token.name);
else:
symtbl[token.name].address = varptr;
varptr = varptr +1
getoken(); #skip past identifier
if token.token == semicolon: getoken() #skip ;
else: error("semicolon expected in declaration")
#======================================================================
# STMTLIST
# <stmtlist> ::= <stmt> { ; <stmt> }
#===============================================================================
def stmtList():
#===============================================================================
stmt()
while (token.token == semicolon):
getoken() #skip ;
stmt()
#======================================================================
# STMT
#===============================================================================
def stmt():
#===============================================================================
""" <stmt> ::= print <expression> | <id> = <expression> | if <expression> | while <expression>
"""
global codeptr
# thisStmtAdr = codeptr # Jump DEMO - not part of Stmt
if token.token == printsym:
printStmt()
elif token.token == idsym:
assignStmt()
elif token.token == assignsym:
getoken()
elif token.token == ifsym:
ifStmt()
elif token.token == elsesym:
elseStmt()
elif token.token == whilesym:
whileStmt()
elif token.token == readint:
readIntStmt()
elif token.token == readch:
readChStmt()
elif token.token == writeint:
writeIntStmt()
elif token.token == writech:
writeChStmt()
elif token.token == semicolon:
getoken()
else:
error("Expected start of a statement")
# emit (0, "return", thisStmtAdr) # Jump DEMO
#===============================================================================
def printStmt():
#===============================================================================
""" <printStmt> ::= print <expression>"""
getoken() # skip "print"
expression() # on return, expr result (at runtime) will be in ACC
emit(0, "writeint", 0) # Memory address 0 is the ACC
if token.token == rightbrace:
print("\n*** Compilation finished ***\n")
#===============================================================================
def assignStmt():
#===============================================================================
"""
<id> = <expression>
"""
whichidentifier = token # Remember which ID on Left
getoken() # Get token after identifier
if token.token == notequals:
srcfile.read()
getoken()
elif token.token == assignsym:
getoken()
elif token.token == jumpeq:
getoken()
elif token.token == printsym:printStmt()
elif token.token == idsym: factor()
else:
error("Expected = in assignment statement")
expression()
# Save result into LHS runtime address
#===============================================================================
def ifStmt():
#if-then-else
#===============================================================================
""" <ifStmt> ::= if <expression>"""
getoken() # skip "if"
emit(0, "compare",60)
expression()
stmt()
emit(0, "return",0)
#===============================================================================
def elseStmt():
#if-then-else
#===============================================================================
""" <elseStmt> ::= else <expression>"""
getoken()
emit(0, "store", 888)
stmt()
#===============================================================================
def whileStmt():
#===============================================================================
""" <whileStmt> ::= while (condition)statement"""
getoken() # skip "if"
emit(0, "compare",50)
expression()
stmt()
emit(0, "increment", 1)
emit(0, "jumpi", 14)
#===============================================================================
def readIntStmt():
#===============================================================================
getoken()
expression() # skip "if"
emit(0, "readint",999)
#===============================================================================
def readChStmt():
#===============================================================================
getoken() # skip "if"
emit(0, "readch",11)
#===============================================================================
def writeIntStmt():
#===============================================================================
getoken() # skip "if"
expression()
emit(0, "writeint",50)
#===============================================================================
def writeChStmt():
#===============================================================================
getoken() # skip "if"
emit(0, "writech",51)
#===============================================================================
def expression():
#===============================================================================
"""
Leaves result in ACC at runtime
Use addresses 999 & 998 as Temporary variables
<expression> ::= <factor> { (+ | - | * | /) <factor> }
"""
factor()
while token.token == plus or token.token == minus or token.token == mpy or token.token == div or token.token == lessthan or token.token == greaterthan or token.token == jumpne or token.token == jumpeq:
op = token # remember +/-
getoken() # skip past +/-
emit(0, "store", 999) # Save current result
factor() # Evaluate next factor
#working
if op.token == plus:
emit(0, "loadv", 999)
emit(0, "add", 999)
emit(0, "store", 999)
if op.token == leftbracket:getoken()
elif op.token == minus: # Subtract - have to swap operand order
emit(0, "store", 998)
emit(0, "load" , 999)
emit(0, "subtract", 998) # Leaves result in Acc
emit(0, "store", 6)
elif op.token == mpy:
emit(0, "store", 998)
emit(0, "load", 999)
emit(0, "mpy", 998)
emit(0, "store", 7)
elif op.token == div:
emit(0, "store", 998)
emit(0, "load", 999)
emit(0, "div", 998)
emit(0, "store", 8)
#===============================================================================
def factor():
#===============================================================================
"""
# FACTOR() - leaves result in ACC at runtime
<factor> ::= (+|-) identifier | number
"""
#Numbers
if token.token == idsym:
emit(0, "load", token.address)
getoken()
elif token.token == number:
emit(0, "loadv", token.value)
getoken()
elif token.token == assignsym:getoken()
elif token.token == semicolon:getoken()
else: error("Start of Factor expected")
#===============================================================================
def program():
#===============================================================================
""" # PROGRAM - Start production of the grammar
# <program> ::= { <id> ; <vars > <stmtlist> }
"""
if token.token == leftbrace: getoken()
else: error(" { expected")
if token.token == idsym: getoken()
else: error("Program name expected")
if token.token == semicolon: getoken()
else: error("Semicolon expected")
if token.token == varsym : vars()
stmtList()
if token.token == number:
factor()
elif token.token == rightbrace:
print("\n*** Compilation finished ***\n")
else: error(" } expected")
# Compiler main function
#======================================================================
def main():
#======================================================================
global line
global srcfile
global outfile
global charIndex
initSymTbl()
srcfile = open('comment.txt', 'r')
line = srcfile.read() # readline
# for line in open('tiny.txt', 'r'):
# if not line.startswith("#"):
# debugScanner = False
charIndex = 0
debugScanner = False
if debugScanner: # Scanner Test Routine - Read a line and display the tokens
getoken()
while token.token is not None: # Skeleton for testing Scanner
printToken(token)
# outfile.write(token)
getoken()
srcfile.close()
sys.exit(1)
else:
getoken() # Parse Program according to the grammar
program() # Call start non-terminal handler
#===============================================================================
# Main Compiler starts here
#===============================================================================
print "#Microcompiler.py v0.2"
emit(0, "load", 0)
emit(0, "constant", "'A'")
emit(0, "constant", 10)
emit(0, "constant", 12)
emit(0, "constant", 25)
emit(0, "constant", -10)
main()
#srcfile = open('tiny.txt', 'r')
#lexer = shlex.shlex(srcfile)
#for token in lexer:
# print repr(token)
#getoken()
| [
[
8,
0,
0.0144,
0.0203,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.027,
0.0017,
0,
0.66,
0.0213,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.0287,
0.0017,
0,
0.66,... | [
"\"\"\" Giovanni's MicroCompiler Demo\n\n<program> ::= { <id> ; <vars > <stmtlist> }\n<vars> ::= V { <id> ; } % DECLARATIONS\n\n<stmtlist> ::= <stmt> { ; <stmt> }\n<stmt> ::= P <id> | <id> = <expr>",
"import sys",
"import shlex",
"tokenName... |
""" Giovanni's MicroCompiler Demo
<program> ::= { <id> ; <vars > <stmtlist> }
<vars> ::= V { <id> ; } % DECLARATIONS
<stmtlist> ::= <stmt> { ; <stmt> }
<stmt> ::= P <id> | <id> = <expr>
<expr> ::= <factor> { (+ | -) <factor> } % No precedence
<factor> ::= (+|-) ID | Number
"""
import sys
import shlex
#===============================================================================
# # Lexical Analyser - the "Scanner" - Define the TokenTypes
#===============================================================================
tokenNames =\
[ "unknownToken", "idsym", "assignsym", "leftbrace", "rightbrace",
"varsym", "semicolon", "whilesym", "leftbracket", "rightbracket",
"printsym", "ifsym", "elsesym", "equals", "notequals", "lessthan", "greaterthan",
"readch", "readint", "writech", "writeint",
"number", "plus", "minus", "mpy", "div", "jumpne", "jumpeq","lessthanequal","greaterthanequal","remainder", "endfile"]
# define the tokens as variables
unknownToken, idsym, assignsym, leftbrace, rightbrace,\
varsym, semicolon, whilesym, leftbracket, rightbracket,\
printsym, ifsym, elsesym, equals, notequals, lessthan, greaterthan,\
readch, readint, writech, writeint,\
number, plus, minus, mpy, div, jumpne, jumpeq, lessthanequal, greaterthanequal,remainder, endfile = range(0, len(tokenNames))
#===============================================================================
class symbol:
#===============================================================================
name = None # String representation
token = None; # Corresponding token
address = 0; # For variables, their runtime address
value = None # on defined for numbers
def __init__(self, name, token, value = 0):
self.name = name
self.token = token
self.address = 0 # for identifiers, their address
self.value = value # for numbers, their value
symtbl = {}; # The Symbol Table, a dictionary of symbols indexed by name
#======================================================================
# GLOBALS for output of Lexical Analyser
# Set by each call to GeToken()
token = None; # A symbol
line = "\n" # the complex source file as a string
charIndex = 0 # the position in the source
linenumber= 0 # The current number
EOF = chr(0)
#======================================================================
# Run Time Code Generation Variables
varptr = 500 # Arbitrary base address of memory for variables
codeptr = 10 # Address to output next instruction (for code)
#===============================================================================
# Symbol Table Management Routines
#===============================================================================
#===============================================================================
def addToSymTbl (name, token):
#===============================================================================
symtbl[name] = symbol(name, token) # Add a new symbol to the dictionary
return symtbl[name]
#===============================================================================
def lookup (thisName):
#===============================================================================
"# Find a given identifier in the Symbol Table, Return the symtbl entry"
if symtbl.has_key(thisName): # thisName has been seen before
return symtbl[thisName] # return the symtbl entry
else: return None
#===============================================================================
def initSymTbl():
#===============================================================================
"# Initialise Symbol Table, and preload reserved words"
addToSymTbl('var', varsym) # VAR
addToSymTbl('while', whilesym) # WHILE
addToSymTbl('for', whilesym) # WHILE
addToSymTbl('print', printsym) # PRINT
addToSymTbl('if', ifsym) # IF
addToSymTbl('else', elsesym) # ELSE
addToSymTbl('readint', readint) #READINT
addToSymTbl('writeint', writeint) #READINT
addToSymTbl('readch', readch) #READINT
addToSymTbl('writech', writech) #READINT
# Now add symbols - NB only single character symbols are here
# multicharacter one like ">=" are still to do
addToSymTbl( '=', assignsym)
addToSymTbl( '#', notequals)
addToSymTbl( '<', lessthan) #jumplt
addToSymTbl( '>', greaterthan) #jumpgt
addToSymTbl( '{', leftbrace )
addToSymTbl( '}', rightbrace)
addToSymTbl( '(', leftbracket)
addToSymTbl( ')', rightbracket)
addToSymTbl( '+', plus )
addToSymTbl( '-', minus)
addToSymTbl( '*', mpy)
addToSymTbl( '/', div)
addToSymTbl( ';', semicolon)
addToSymTbl( '%', remainder)
addToSymTbl( EOF, endfile)
#multicharacter one like ">=" are still to do
addToSymTbl( '!=', jumpne)
addToSymTbl( '==', jumpeq)
addToSymTbl( '<=', lessthanequal) #jumplt
addToSymTbl( '>=', greaterthanequal) #jumpgt
#===============================================================================
# Scanner Diagnostics
#===============================================================================
def printToken(tok):
#===============================================================================
" - display the specified token."
if tok.token == idsym:
print "Token = %10s, %-10s adr = %3d" %\
(tokenNames[tok.token], tok.name, tok.address)
elif tok.token == number:
print "Token = %10s %d" % (tokenNames[tok.token], tok.value)
else:
print "Token = %10s" % tokenNames[tok.token]
#==============================?=================================================
def dumpSymTbl():
#===============================================================================
""" Dump all the tokens in the symboltable """
print(" *** Symbol Table ***")
for name in symtbl.keys(): # keys is a list of the names (printable form of tokens)
tok = symtbl[name]
if tok.token == idsym:
printToken(tok)
#===============================================================================
def getch():
#===============================================================================
global line
global charIndex
global linenumber
while True:
if charIndex < len(line): # See if used up current line
ch = line[charIndex] # if not, get character
charIndex = charIndex+1 # & move pointer for next time
else:
#line = srcfile.readline()
if line == "": line = EOF
#print "--> ",
line = raw_input() +"\n" # read new line, adding \n so it's like f.readline()
charIndex = 0 # & reset character pointer
linenumber = linenumber + 1
continue
if ch == "\n":
ch = " " # A newline is a token separator
if ch == "?":
dumpSymTbl()
continue
if ch == "#":
print "#Comment Found"
srcfile.read()
print "#Read next line"
return ch
#===============================================================================
def ungetch():
#===============================================================================
""" Unget the next character peeked at when building variables, numbers
and when distinguishing between >= and > ...
"""
global charIndex;
charIndex = charIndex-1;
#===============================================================================
def getoken():
#===============================================================================
""" GETOKEN - Put next token into the global TOKEN """
global token
ch = getch() # skip whitespace
while ch in ["\t", " ", "\n", "#"]:
ch = getch()
# If ch is alphabetic then this is start of reserved word or an identifier
if ch.isalpha(): # Letter therefore it's either identifier or reserved word
name = ""
while ch.isalpha() or ch.isdigit() or ch == "_":
name = name + ch
ch = getch()
ungetch() # let terminator be used next time
token = lookup(name) # See if token's known
if token is None: # if not
token = addToSymTbl(name, idsym) # add as 'idsym'-IDENTIFIER
return # we've set token.token to either id or tokentype of reserved word
#---------------------------------------------------------------------
# If it's numeric return TOKEN=number & token.value = binary value
elif ch.isdigit():
# In the real version, build number and don't forget to end with ungetch()
token = symbol(ch, number, value = int(ch)) # simplistic SINGLE DIGIT Ascii to Binary
return
#---------------------------------------------------------------------
# Single character tokens
elif ch in ["#", "{", "}", "(", ")", "+" , "-", "*", "/", ";","%", EOF]:
token = lookup(ch) # preloaded with appropriate token
elif ch in ["!"]:
ch = getch()
char = "!"
nEqual = "!="
if ch == "=":
char = nEqual
ch = getch()
else:
token = lookup(ch)
ungetch()
token = lookup(char)
if token is None:
token = addToSymTbl(char, idsym)
return
elif ch in ["="]:
ch = getch()
char = "="
Equal = "=="
if ch == "=":
char = Equal
ch = getch()
else:
token = lookup(ch)
ungetch()
token = lookup(char)
if token is None:
token = addToSymTbl(char, idsym)
return
elif ch in ["<"]:
ch = getch()
char = "<"
lessthanEqual = "<="
if ch == "=":
char = lessthanEqual
ch = getch()
else:
token = lookup(ch)
ungetch()
token = lookup(char)
if token is None:
token = addToSymTbl(char, idsym)
return
elif ch in [">"]:
ch = getch()
char = ">"
greatthanEqual = ">="
if ch == "=":
char = greatthanEqual
ch = getch()
else:
token = lookup(ch)
ungetch()
token = lookup(char)
if token is None:
token = addToSymTbl(char, idsym)
return
else:
print "Unknown character -->%s<- decimal %d" % (ch,ord(ch))
sys.exit(1) # Abort Compilation
#======================================================================
# THE GRAMMAR
# <program> ::= { <id> ; <vars > <stmtlist> }
# <vars> ::= var { <id> ; } % DECLARATIONS
# <array> ::= [<expr>]
# <stmtlist> ::= <stmt> { ; <stmt> }
# <stmt> ::= print <id>
# <id> = <expr>
# <expr> ::= <factor> { (+ | -) <factor> } % No precedence
# <factor> ::= [+/-] ID | Number
#======================================================================
# Centralised Parser Error Message handler
#======================================================================
#===============================================================================
def error (msg):
#===============================================================================
print line
print "-" * charIndex,"^"
print("Error on %d - %s\n" % (number, msg))
printToken(token)
print("\n")
#===============================================================================
def emit (memadr, opcode, parameter):
#===============================================================================
"""EMIT CODE - Emit a of code with a Parameter
if first arg is zero - (the memory address), use and incr CODEPTR"""
global codeptr
if (memadr == 0):
memadr = codeptr
codeptr = codeptr+1
print "%6d %-8s %-7s" % (memadr, opcode, parameter)
#======================================================================
# VARIABLE DECLARATIONS
# <vars> ::= V { <id> ; }
#===============================================================================
def vars() :
#===============================================================================
global varptr;
getoken(); #skip VARSYM - already been recognised
while (token.token == idsym):
if token.address != 0:
print("%c already declared\n", token.name);
else:
symtbl[token.name].address = varptr;
varptr = varptr +1
getoken(); #skip past identifier
if token.token == semicolon: getoken() #skip ;
else: error("semicolon expected in declaration")
#======================================================================
# STMTLIST
# <stmtlist> ::= <stmt> { ; <stmt> }
#===============================================================================
def stmtList():
#===============================================================================
stmt()
while (token.token == semicolon):
getoken() #skip ;
stmt()
#======================================================================
# STMT
#===============================================================================
def stmt():
#===============================================================================
""" <stmt> ::= print <expression> | <id> = <expression> | if <expression> | while <expression>
"""
global codeptr
# thisStmtAdr = codeptr # Jump DEMO - not part of Stmt
if token.token == printsym:
printStmt()
elif token.token == idsym:
assignStmt()
elif token.token == assignsym:
getoken()
elif token.token == ifsym:
ifStmt()
elif token.token == elsesym:
elseStmt()
elif token.token == whilesym:
whileStmt()
elif token.token == readint:
readIntStmt()
elif token.token == readch:
readChStmt()
elif token.token == writeint:
writeIntStmt()
elif token.token == writech:
writeChStmt()
elif token.token == jumpne:
expression()
elif token.token == jumpeq:
expression()
elif token.token == lessthanequal:
expression()
elif token.token == greaterthanequal:
expression()
elif token.token == rightbrace:getoken()
elif token.token == semicolon:
getoken()
else:
error("Expected start of a statement")
# emit (0, "return", thisStmtAdr) # Jump DEMO
#===============================================================================
def printStmt():
#===============================================================================
""" <printStmt> ::= print <expression>"""
getoken() # skip "print"
expression() # on return, expr result (at runtime) will be in ACC
emit(0, "writeint", 0) # Memory address 0 is the ACC
if token.token == rightbrace:
print("#\n*** Compilation finished ***\n")
#===============================================================================
def assignStmt():
#===============================================================================
"""
<id> = <expression>
"""
whichidentifier = token # Remember which ID on Left
getoken() # Get token after identifier
if token.token == notequals: # skip # then read next line
srcfile.read()
getoken()
elif token.token == assignsym: #if the next token is =
expression()
elif token.token == idsym: factor()
elif token.token == ifsym: stmt()
elif token.token == whilesym: stmt()
elif token.token == jumpeq: print("#")
elif token.token == jumpne: print("#")
elif token.token == lessthanequal: print("#")
elif token.token == greaterthanequal: print("#")
elif token.token == semicolon: getoken()
else:
error("Expected = in assignment statement")
expression()
# Save result into LHS runtime address
#===============================================================================
def ifStmt():
#if-then-else
#===============================================================================
""" <ifStmt> ::= if <expression>"""
getoken() # skip "if"
expression()
stmt()
#===============================================================================
def elseStmt():
#if-then-else
#===============================================================================
""" <elseStmt> ::= else <expression>"""
getoken()
emit(0, "store", 888)
stmt()
#===============================================================================
def whileStmt():
#===============================================================================
""" <whileStmt> ::= while (condition)statement"""
print("#While statement\n")
getoken() # skip "while"
expression()
emit(0, "compare", 204)
stmt()
emit(0, "increment", 1)
emit(0, "jumpi", 14)
#===============================================================================
def readIntStmt():
#===============================================================================
getoken()
expression()
emit(0, "readint",999)
#===============================================================================
def readChStmt():
#===============================================================================
getoken()
emit(0, "readch",11)
#===============================================================================
def writeIntStmt():
#===============================================================================
getoken() # skip "if"
expression()
emit(0, "writeint",50)
#===============================================================================
def writeChStmt():
#===============================================================================
getoken() # skip "if"
emit(0, "writech",51)
#===============================================================================
def expression():
#===============================================================================
"""
Leaves result in ACC at runtime
Use addresses 999 & 998 as Temporary variables
<expression> ::= <factor> { (+ | - | * | /) <factor> }
"""
factor()
while token.token == plus or token.token == minus or token.token == mpy or token.token == div or token.token == lessthan or token.token == greaterthan or token.token == jumpeq or token.token == jumpne or token.token == lessthanequal or token.token == greaterthanequal:
op = token # remember +/-
getoken() # skip past +/-
#emit(0, "store", 2) # Save current result
factor() # Evaluate next factor
#working
if op.token == plus: #+
emit(0, "loadv", 999)
emit(0, "add", 999)
emit(0, "store", 999)
elif op.token == minus: # - Subtract - have to swap operand order
emit(0, "store", 998)
emit(0, "load" , 999)
emit(0, "subtract", 998) # Leaves result in Acc
emit(0, "store", 880)
elif op.token == mpy: #*
emit(0, "store", 998)
emit(0, "load", 999)
emit(0, "mpy", 998)
emit(0, "store", 881)
elif op.token == div: #/
emit(0, "store", 998)
emit(0, "load", 999)
emit(0, "div", 998)
emit(0, "store", 882)
elif op.token == remainder: #%
emit(0, "store", 998)
emit(0, "load", 999)
emit(0, "mod", 998)
emit(0, "store", 883)
elif op.token == jumpeq: #==
print("#==\n")
emit(0, "compare", 11)
emit(0, "jumpeq", 310)
if token.token == idsym:getoken()
if token.token == assignsym:getoken()
emit(310, "loadv", token.value)
emit(311, "store", 401)
emit(312, "return", 0)
getoken()
getoken()
elif op.token == jumpne: #!=
print("#!=\n")
emit(0, "compare", 204)
emit(0, "jumpne", 300)
if token.token == idsym:getoken()
if token.token == assignsym:getoken()
emit(300, "loadv", token.value)
emit(301, "store", 400)
emit(302, "return", 0)
getoken()
getoken()
elif op.token == lessthanequal: #<=
print("#<=\n")
emit(0, "compare", 204)
emit(0, "jumplt", 320)
emit(0, "compare", 204)
emit(0, "jumpeq", 320)
if token.token == idsym:getoken()
if token.token == assignsym:getoken()
emit(320, "loadv", token.value)
emit(321, "store", 402)
emit(322, "return", 0)
getoken()
getoken()
elif op.token == greaterthanequal: #>=
print("#>=\n")
emit(0, "compare", 204)
emit(0, "jumpgt", 330)
emit(0, "compare", 204)
emit(0, "jumpeq", 330)
if token.token == idsym:getoken()
if token.token == assignsym:getoken()
emit(330, "loadv", token.value)
emit(331, "store", 403)
emit(332, "return", 0)
getoken()
if token.token == semicolon:getoken()
#===============================================================================
def factor():
#===============================================================================
"""
# FACTOR() - leaves result in ACC at runtime
<factor> ::= (+|-) identifier | number
"""
#Numbers
if token.token == idsym:
emit(0, "load", token.address)
getoken()
elif token.token == number:
emit(0, "loadv", token.value)
emit(0, "store", 200+token.value)
getoken()
elif token.token == assignsym:getoken()
elif token.token == jumpeq:
print("#==")
elif token.token == jumpne:
print("")
elif token.token == lessthanequal:
print("#<=")
elif token.token == greaterthanequal:
print("#<=")
elif token.token == lessthan:
print("#<")
elif token.token == ifsym:
ifStmt()
elif token.token == elsesym:
elseStmt()
elif token.token == whilesym:
whileStmt()
elif token.token == semicolon: getoken()
else: error("Start of Factor expected")
#===============================================================================
def program():
#===============================================================================
""" # PROGRAM - Start production of the grammar
# <program> ::= { <id> ; <vars > <stmtlist> }
"""
if token.token == leftbrace: getoken()
else: error(" { expected")
if token.token == idsym: getoken()
else: error("Program name expected")
if token.token == semicolon: getoken()
else: error("Semicolon expected")
if token.token == varsym : vars()
stmtList()
if token.token == rightbrace:
print("\n")
else: error(" } expected")
if token.token == rightbrace:
print("\n")
# Compiler main function
#======================================================================
def main():
#======================================================================
global line
global srcfile
global outfile
global charIndex
initSymTbl()
srcfile = open('character.txt', 'r')
line = srcfile.read() # readline
# for line in open('tiny.txt', 'r'):
# if not line.startswith("#"):
# debugScanner = False
charIndex = 0
debugScanner = False
if debugScanner: # Scanner Test Routine - Read a line and display the tokens
getoken()
while token.token is not None: # Skeleton for testing Scanner
printToken(token)
# outfile.write(token)
getoken()
srcfile.close()
sys.exit(1)
else:
getoken() # Parse Program according to the grammar
program() # Call start non-terminal handler
#===============================================================================
# Main Compiler starts here
#===============================================================================
print "#Microcompiler.py v0.2"
emit(0, "load", 0)
main()
#srcfile = open('tiny.txt', 'r')
#lexer = shlex.shlex(srcfile)
#for token in lexer:
# print repr(token)
getoken()
| [
[
8,
0,
0.0115,
0.0163,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0217,
0.0014,
0,
0.66,
0.0233,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.0231,
0.0014,
0,
0.66... | [
"\"\"\" Giovanni's MicroCompiler Demo\n\n<program> ::= { <id> ; <vars > <stmtlist> }\n<vars> ::= V { <id> ; } % DECLARATIONS\n\n<stmtlist> ::= <stmt> { ; <stmt> }\n<stmt> ::= P <id> | <id> = <expr>",
"import sys",
"import shlex",
"tokenName... |
""" Giovanni's MicroCompiler Demo
<program> ::= { <id> ; <vars > <stmtlist> }
<vars> ::= V { <id> ; } % DECLARATIONS
<stmtlist> ::= <stmt> { ; <stmt> }
<stmt> ::= P <id> | <id> = <expr>
<expr> ::= <factor> { (+ | -) <factor> } % No precedence
<factor> ::= (+|-) ID | Number
"""
import sys
import shlex
#===============================================================================
# # Lexical Analyser - the "Scanner" - Define the TokenTypes
#===============================================================================
tokenNames =\
[ "unknownToken", "idsym", "assignsym", "leftbrace", "rightbrace",
"varsym", "semicolon", "whilesym", "leftbracket", "rightbracket","leftparen","rightparen",
"printsym", "ifsym", "elsesym", "equals", "notequals", "lessthan", "greaterthan",
"readch", "readint", "writech", "writeint","comma","dot","appendsym",
"number", "plus", "minus", "mpy", "div", "jumpne", "jumpeq","lessthanequal","greaterthanequal", "endfile"]
# define the tokens as variables
unknownToken, idsym, assignsym, leftbrace, rightbrace,\
varsym, semicolon, whilesym, leftbracket, rightbracket, leftparen, rightparen,\
printsym, ifsym, elsesym, equals, notequals, lessthan, greaterthan,\
readch, readint, writech, writeint,comma,dot,appendsym,\
number, plus, minus, mpy, div, jumpne, jumpeq, lessthanequal, greaterthanequal, endfile = range(0, len(tokenNames))
#===============================================================================
class symbol:
#===============================================================================
name = None # String representation
token = None; # Corresponding token
address = 0; # For variables, their runtime address
value = None # on defined for numbers
def __init__(self, name, token, value = 0):
self.name = name
self.token = token
self.address = 0 # for identifiers, their address
self.value = value # for numbers, their value
symtbl = {}; # The Symbol Table, a dictionary of symbols indexed by name
#======================================================================
# GLOBALS for output of Lexical Analyser
# Set by each call to GeToken()
token = None; # A symbol
line = "\n" # the complex source file as a string
charIndex = 0 # the position in the source
linenumber= 0 # The current number
EOF = chr(0)
#======================================================================
# Run Time Code Generation Variables
varptr = 500 # Arbitrary base address of memory for variables
codeptr = 10 # Address to output next instruction (for code)
#===============================================================================
# Symbol Table Management Routines
#===============================================================================
#===============================================================================
def addToSymTbl (name, token):
#===============================================================================
symtbl[name] = symbol(name, token) # Add a new symbol to the dictionary
return symtbl[name]
#===============================================================================
def lookup (thisName):
#===============================================================================
"# Find a given identifier in the Symbol Table, Return the symtbl entry"
if symtbl.has_key(thisName): # thisName has been seen before
return symtbl[thisName] # return the symtbl entry
else: return None
#===============================================================================
def initSymTbl():
#===============================================================================
"# Initialise Symbol Table, and preload reserved words"
addToSymTbl('var', varsym) # VAR
addToSymTbl('while', whilesym) # WHILE
addToSymTbl('for', whilesym) # WHILE
addToSymTbl('print', printsym) # PRINT
addToSymTbl('append', appendsym)
addToSymTbl('if', ifsym) # IF
addToSymTbl('else', elsesym) # ELSE
addToSymTbl('readint', readint) #READINT
addToSymTbl('writeint', writeint) #READINT
addToSymTbl('readch', readch) #READINT
addToSymTbl('writech', writech) #READINT
# Now add symbols - NB only single character symbols are here
# multicharacter one like ">=" are still to do
addToSymTbl( '=', assignsym)
addToSymTbl( '#', notequals)
addToSymTbl( '<', lessthan) #jumplt
addToSymTbl( '>', greaterthan) #jumpgt
addToSymTbl( '{', leftbrace )
addToSymTbl( '}', rightbrace)
addToSymTbl( '(', leftbracket)
addToSymTbl( ')', rightbracket)
addToSymTbl( '[', leftparen)
addToSymTbl( ']', rightparen)
addToSymTbl( '+', plus )
addToSymTbl( '-', minus)
addToSymTbl( '*', mpy)
addToSymTbl( '/', div)
addToSymTbl( ';', semicolon)
addToSymTbl( EOF, endfile)
addToSymTbl( ',', comma)
addToSymTbl( '.', dot)
#multicharacter one like ">=" are still to do
addToSymTbl( '==', jumpeq)
addToSymTbl( '!=', jumpne)
addToSymTbl( '<=', lessthanequal) #jumplt
addToSymTbl( '>=', greaterthanequal) #jumpgt
#===============================================================================
# Scanner Diagnostics
#===============================================================================
def printToken(tok):
#===============================================================================
" - display the specified token."
if tok.token == idsym:
print "Token = %10s, %-10s adr = %3d" %\
(tokenNames[tok.token], tok.name, tok.address)
elif tok.token == number:
print "Token = %10s %d" % (tokenNames[tok.token], tok.value)
else:
print "Token = %10s" % tokenNames[tok.token]
#==============================?=================================================
def dumpSymTbl():
#===============================================================================
""" Dump all the tokens in the symboltable """
print(" *** Symbol Table ***")
for name in symtbl.keys(): # keys is a list of the names (printable form of tokens)
tok = symtbl[name]
if tok.token == idsym:
printToken(tok)
#===============================================================================
def getch():
#===============================================================================
global line
global charIndex
global linenumber
while True:
if charIndex < len(line): # See if used up current line
ch = line[charIndex] # if not, get character
charIndex = charIndex+1 # & move pointer for next time
else:
#line = srcfile.readline()
if line == "": line = EOF
print "--> ",
line = raw_input() +"\n" # read new line, adding \n so it's like f.readline()
charIndex = 0 # & reset character pointer
linenumber = linenumber + 1
continue
if ch == "\n":
ch = " " # A newline is a token separator
if ch == "?":
dumpSymTbl()
continue
return ch
#===============================================================================
def ungetch():
#===============================================================================
""" Unget the next character peeked at when building variables, numbers
and when distinguishing between >= and > ...
"""
global charIndex;
charIndex = charIndex-1;
#===============================================================================
def getoken():
#===============================================================================
""" GETOKEN - Put next token into the global TOKEN """
global token
ch = getch() # skip whitespace
while ch in ["\t", " ", "\n", "#"]:
ch = getch()
# If ch is alphabetic then this is start of reserved word or an identifier
if ch.isalpha(): # Letter therefore it's either identifier or reserved word
name = ""
while ch.isalpha() or ch.isdigit() or ch == "_":
name = name + ch
ch = getch()
ungetch() # let terminator be used next time
token = lookup(name) # See if token's known
if token is None: # if not
token = addToSymTbl(name, idsym) # add as 'idsym'-IDENTIFIER
return # we've set token.token to either id or tokentype of reserved word
#---------------------------------------------------------------------
# If it's numeric return TOKEN=number & token.value = binary value
elif ch.isdigit():
# In the real version, build number and don't forget to end with ungetch()
token = symbol(ch, number, value = int(ch)) # simplistic SINGLE DIGIT Ascii to Binary
return
#---------------------------------------------------------------------
# Single character tokens
elif ch in ["=", "#", "<", ">", "{", "}", "(", ")", "[","]", "+" , "-", "*", "/", ";","!", "==",",",".", EOF]:
token = lookup(ch) # preloaded with appropriate token
else:
print "Unknown character -->%s<- decimal %d" % (ch,ord(ch))
sys.exit(1) # Abort Compilation
#======================================================================
# THE GRAMMAR
# <program> ::= { <id> ; <vars > <stmtlist> }
# <vars> ::= var { <id> ; } % DECLARATIONS
# <array> ::= [<expr>]
# <stmtlist> ::= <stmt> { ; <stmt> }
# <stmt> ::= print <id>
# <id> = <expr>
# <expr> ::= <factor> { (+ | - | * | /) <factor> } % No precedence
# <factor> ::= [+/-] ID | Number
#======================================================================
# Centralised Parser Error Message handler
#======================================================================
#===============================================================================
def error (msg):
#===============================================================================
print line
print "-" * charIndex,"^"
print("Error on %d - %s\n" % (number, msg))
printToken(token)
print("\n")
#===============================================================================
def emit (memadr, opcode, parameter):
#===============================================================================
"""EMIT CODE - Emit a of code with a Parameter
if first arg is zero - (the memory address), use and incr CODEPTR"""
global codeptr
if (memadr == 0):
memadr = codeptr
codeptr = codeptr+1
print "%6d %-8s %-7s" % (memadr, opcode, parameter)
#======================================================================
# VARIABLE DECLARATIONS
# <vars> ::= V { <id> ; }
#===============================================================================
def vars() :
#===============================================================================
global varptr;
getoken(); #skip VARSYM - already been recognised
while (token.token == idsym):
if token.address != 0:
print("%c already declared\n", token.name);
else:
symtbl[token.name].address = varptr;
varptr = varptr +1
getoken(); #skip past identifier
if token.token == assignsym:assignStmt()
if token.token == semicolon: getoken() #skip ;
else: error("semicolon expected in declaration")
#===============================================================================
def array():
#a=[1,2,3];
#a=append(4);
#print a;
#===============================================================================
global array;
list =[];
#a=[1,2,3];
while (token.token == number):
print("#array address")
emit(0, "loadv", token.value)
list.append(token.value)
emit(0, "store", token.value+100)
emit(0, "push", token.value+200)
getoken()
if token.token == comma:getoken()
if token.token == rightparen:getoken()
if token.token == semicolon:getoken()
print ("\n"+ "#This is a list of array from txt\n" + "#"+str(list) + "\n");
if token.token == idsym:getoken()
if token.token == dot:getoken()
if token.token == appendsym:getoken()
if token.token == leftbracket:getoken()
while( token.token == number):
print("#store new value to list")
emit(0, "load", token.value)
list.append(token.value)
emit(0, "store", 104)
emit(0, "push", token.value+200)
getoken()
print("\n"+ "#Now the list have new value added to list" + "\n#"+str(list)+"\n")
if token.token == rightbracket:getoken()
if token.token == semicolon:getoken()
#======================================================================
# STMTLIST
# <stmtlist> ::= <stmt> { ; <stmt> }
#===============================================================================
def stmtList():
#===============================================================================
stmt()
while (token.token == semicolon):
getoken() #skip ;
stmt()
#======================================================================
# STMT
#===============================================================================
def stmt():
#===============================================================================
""" <stmt> ::= print <expression> | <id> = <expression> | if <expression> | while <expression>
"""
global codeptr
thisStmtAdr = codeptr # Jump DEMO - not part of Stmt
if token.token == printsym:
printStmt()
if token.token == varsym:
vars()
elif token.token == idsym:
assignStmt()
else:
error("Expected start of a statement")
# emit (0, "return", thisStmtAdr) # Jump DEMO
#===============================================================================
def printStmt():
#===============================================================================
""" <printStmt> ::= print <expression>"""
getoken() # skip "print"
if token.token == idsym: getoken()
emit(0, "writeint", 100) # Memory address 0 is the ACC
if token.token == semicolon: getoken()
if token.token == rightbrace:
print("")
#===============================================================================
def assignStmt():
#===============================================================================
"""
<id> = <expression>
"""
whichidentifier = token # Remember which ID on Left
getoken() # Get token after identifier
if token.token == notequals:
srcfile.read()
# getoken()
elif token.token == assignsym:
getoken()
elif token.token == number:
factor()
elif token.token == leftparen: # [
array()
else:
error("Expected = in assignment statement")
expression()
# Save result into LHS runtime address
#===============================================================================
def expression():
#===============================================================================
"""
Leaves result in ACC at runtime
Use addresses 999 & 998 as Temporary variables
<expression> ::= <factor> { (+ | - | * | /) <factor> }
"""
factor()
while token.token == plus or token.token == jumpeq:
op = token # remember +/-
getoken() # skip past +/-
emit(0, "store", 999) # Save current result
if token.token == jumpeq:
emit(0, "store", 998)
emit(0, "compare", 999)
emit(0, "jumpeq", 83)
#===============================================================================
def factor():
#===============================================================================
"""
# FACTOR() - leaves result in ACC at runtime
<factor> ::= (+|-) identifier | number
"""
#Numbers
if token.token == idsym:
emit(0, "load", token.address)
getoken()
elif token.token == number:
print("# Store value")
emit(0, "loadv", token.value)
emit(0, "store", 1)
print(" ")
getoken()
elif token.token == leftparen:getoken()
elif token.token == assignsym:getoken()
elif token.token == semicolon:getoken()
else: error("Start of Factor expected")
#===============================================================================
def program():
#===============================================================================
""" # PROGRAM - Start production of the grammar
# <program> ::= { <id> ; <vars > <stmtlist> }
"""
if token.token == leftbrace: getoken()
else: error(" { expected")
if token.token == idsym: getoken()
else: error("Program name expected")
if token.token == semicolon: getoken()
else: error("Semicolon expected")
stmtList()
if token.token == rightparen: getoken()
elif token.token == number: array()
# else: error(" ] expected")
if token.token == printsym:printStmt()
if token.token == rightbrace:
print("\n#*** Compilation finished ***\n")
else: error(" } expected")
# Compiler main function
#======================================================================
def main():
#======================================================================
global line
global srcfile
global outfile
global charIndex
initSymTbl()
srcfile = open('declare_array.txt', 'r')
line = srcfile.read() # readline
charIndex = 0
debugScanner = False
if debugScanner: # Scanner Test Routine - Read a line and display the tokens
getoken()
while token.token is not None: # Skeleton for testing Scanner
printToken(token)
# outfile.write(token)
getoken()
srcfile.close()
sys.exit(1)
else:
getoken() # Parse Program according to the grammar
program() # Call start non-terminal handler
#===============================================================================
# Main Compiler starts here
#===============================================================================
print "#Microcompiler.py v0.2"
emit(0, "load", 0)
#emit(0, "constant", "'A'")
#emit(0, "constant", 10)
emit(0, "constant", 12)
#emit(0, "constant", 25)
#emit(0, "constant", -10)
main()
"""srcfile = open('tiny.txt', 'r')
lexer = shlex.shlex(srcfile)
for token in lexer:
print repr(token)
"""
#getoken()
| [
[
8,
0,
0.0152,
0.0215,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0286,
0.0018,
0,
0.66,
0.0263,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.0304,
0.0018,
0,
0.66... | [
"\"\"\" Giovanni's MicroCompiler Demo\n\n<program> ::= { <id> ; <vars > <stmtlist> }\n<vars> ::= V { <id> ; } % DECLARATIONS\n\n<stmtlist> ::= <stmt> { ; <stmt> }\n<stmt> ::= P <id> | <id> = <expr>",
"import sys",
"import shlex",
"tokenName... |
'''
Created on Jun 23, 2014
@author: Brian
'''
""" Giovanni's MicroCompiler Demo
<program> ::= { <id> ; <vars > <stmtlist> }
<vars> ::= V { <id> ; } % DECLARATIONS
<stmtlist> ::= <stmt> { ; <stmt> }
<stmt> ::= P <id> | <id> = <expr>
<expr> ::= <factor> { (+ | -) <factor> } % No precedence
<factor> ::= (+|-) ID | Number
"""
import sys
import shlex
#===============================================================================
# # Lexical Analyser - the "Scanner" - Define the TokenTypes
#===============================================================================
tokenNames =\
[ "unknownToken", "idsym", "assignsym", "leftbrace", "rightbrace",
"varsym", "semicolon", "whilesym", "leftbracket", "rightbracket",
"printsym", "ifsym", "elsesym", "equals", "notequals", "lessthan", "greaterthan",
"readch", "readint", "writech", "writeint",
"number", "plus", "minus", "mpy", "div", "jumpne", "jumpeq","lessthanequal","greaterthanequal","ex","remainder", "endfile"]
# define the tokens as variables
unknownToken, idsym, assignsym, leftbrace, rightbrace,\
varsym, semicolon, whilesym, leftbracket, rightbracket,\
printsym, ifsym, elsesym, equals, notequals, lessthan, greaterthan,\
readch, readint, writech, writeint,\
number, plus, minus, mpy, div, jumpne, jumpeq, lessthanequal, greaterthanequal,ex,remainder, endfile = range(0, len(tokenNames))
#===============================================================================
class symbol:
#===============================================================================
name = None # String representation
token = None; # Corresponding token
address = 0; # For variables, their runtime address
value = None # on defined for numbers
def __init__(self, name, token, value = 0):
self.name = name
self.token = token
self.address = 0 # for identifiers, their address
self.value = value # for numbers, their value
symtbl = {}; # The Symbol Table, a dictionary of symbols indexed by name
#======================================================================
# GLOBALS for output of Lexical Analyser
# Set by each call to GeToken()
token = None; # A symbol
line = "\n" # the complex source file as a string
charIndex = 0 # the position in the source
linenumber= 0 # The current number
EOF = chr(0)
#======================================================================
# Run Time Code Generation Variables
varptr = 500 # Arbitrary base address of memory for variables
codeptr = 10 # Address to output next instruction (for code)
#===============================================================================
# Symbol Table Management Routines
#===============================================================================
#===============================================================================
def addToSymTbl (name, token):
#===============================================================================
symtbl[name] = symbol(name, token) # Add a new symbol to the dictionary
return symtbl[name]
#===============================================================================
def lookup (thisName):
#===============================================================================
"# Find a given identifier in the Symbol Table, Return the symtbl entry"
if symtbl.has_key(thisName): # thisName has been seen before
return symtbl[thisName] # return the symtbl entry
else: return None
#===============================================================================
def initSymTbl():
#===============================================================================
"# Initialise Symbol Table, and preload reserved words"
addToSymTbl('var', varsym) # VAR
addToSymTbl('while', whilesym) # WHILE
addToSymTbl('for', whilesym) # WHILE
addToSymTbl('print', printsym) # PRINT
addToSymTbl('if', ifsym) # IF
addToSymTbl('else', elsesym) # ELSE
addToSymTbl('readint', readint) #READINT
addToSymTbl('writeint', writeint) #READINT
addToSymTbl('readch', readch) #READINT
addToSymTbl('writech', writech) #READINT
# Now add symbols - NB only single character symbols are here
# multicharacter one like ">=" are still to do
addToSymTbl( '=', assignsym)
addToSymTbl( '#', notequals)
addToSymTbl( '<', lessthan) #jumplt
addToSymTbl( '>', greaterthan) #jumpgt
addToSymTbl( '{', leftbrace )
addToSymTbl( '}', rightbrace)
addToSymTbl( '(', leftbracket)
addToSymTbl( ')', rightbracket)
addToSymTbl( '+', plus )
addToSymTbl( '-', minus)
addToSymTbl( '*', mpy)
addToSymTbl( '/', div)
addToSymTbl( ';', semicolon)
addToSymTbl( '!', ex)
addToSymTbl( '%', remainder)
addToSymTbl( EOF, endfile)
#multicharacter one like ">=" are still to do
addToSymTbl( '==', jumpeq)
addToSymTbl( '!=', jumpne)
addToSymTbl( '<=', lessthanequal) #jumplt
addToSymTbl( '>=', greaterthanequal) #jumpgt
#===============================================================================
# Scanner Diagnostics
#===============================================================================
def printToken(tok):
#===============================================================================
" - display the specified token."
if tok.token == idsym:
print "Token = %10s, %-10s adr = %3d" %\
(tokenNames[tok.token], tok.name, tok.address)
elif tok.token == number:
print "Token = %10s %d" % (tokenNames[tok.token], tok.value)
else:
print "Token = %10s" % tokenNames[tok.token]
#==============================?=================================================
def dumpSymTbl():
#===============================================================================
""" Dump all the tokens in the symboltable """
print(" *** Symbol Table ***")
for name in symtbl.keys(): # keys is a list of the names (printable form of tokens)
tok = symtbl[name]
if tok.token == idsym:
printToken(tok)
#===============================================================================
def getch():
#===============================================================================
global line
global charIndex
global linenumber
while True:
if charIndex < len(line): # See if used up current line
ch = line[charIndex] # if not, get character
charIndex = charIndex+1 # & move pointer for next time
else:
#line = srcfile.readline()
if line == "": line = EOF
#print "--> ",
line = raw_input() +"\n" # read new line, adding \n so it's like f.readline()
charIndex = 0 # & reset character pointer
linenumber = linenumber + 1
continue
if ch == "\n":
ch = " " # A newline is a token separator
if ch == "?":
dumpSymTbl()
continue
if ch == "#":
print "#Comment Found"
srcfile.read()
print "#Read next line"
return ch
#===============================================================================
def ungetch():
#===============================================================================
""" Unget the next character peeked at when building variables, numbers
and when distinguishing between >= and > ...
"""
global charIndex;
charIndex = charIndex-1;
#===============================================================================
def getoken():
#===============================================================================
""" GETOKEN - Put next token into the global TOKEN """
global token
ch = getch() # skip whitespace
while ch in ["\t", " ", "\n", "#"]:
ch = getch()
# If ch is alphabetic then this is start of reserved word or an identifier
if ch.isalpha(): # Letter therefore it's either identifier or reserved word
name = ""
while ch.isalpha() or ch.isdigit() or ch == "_":
name = name + ch
ch = getch()
ungetch() # let terminator be used next time
token = lookup(name) # See if token's known
if token is None: # if not
token = addToSymTbl(name, idsym) # add as 'idsym'-IDENTIFIER
return # we've set token.token to either id or tokentype of reserved word
#---------------------------------------------------------------------
# If it's numeric return TOKEN=number & token.value = binary value
elif ch.isdigit():
# In the real version, build number and don't forget to end with ungetch()
token = symbol(ch, number, value = int(ch)) # simplistic SINGLE DIGIT Ascii to Binary
return
#---------------------------------------------------------------------
# Single character tokens
elif ch in ["#", "{", "}", "(", ")", "+" , "-", "*", "/", ";","%", EOF]:
token = lookup(ch) # preloaded with appropriate token
elif ch in ["!"]:
ch = getch()
char = "!"
nEqual = "!="
if ch == "=":
char = nEqual
ch = getch()
else:
token = lookup(ch)
ungetch()
token = lookup(char)
if token is None:
token = addToSymTbl(char, idsym)
return
elif ch in ["="]:
ch = getch()
char = "="
Equal = "=="
if ch == "=":
char = Equal
ch = getch()
else:
token = lookup(ch)
ungetch()
token = lookup(char)
if token is None:
token = addToSymTbl(char, idsym)
return
elif ch in ["<"]:
ch = getch()
char = "<"
lessthanEqual = "<="
if ch == "=":
char = lessthanEqual
ch = getch()
else:
token = lookup(ch)
ungetch()
token = lookup(char)
if token is None:
token = addToSymTbl(char, idsym)
return
elif ch in [">"]:
ch = getch()
char = ">"
greatthanEqual = ">="
if ch == "=":
char = greatthanEqual
ch = getch()
else:
token = lookup(ch)
ungetch()
token = lookup(char)
if token is None:
token = addToSymTbl(char, idsym)
return
else:
print "Unknown character -->%s<- decimal %d" % (ch,ord(ch))
sys.exit(1) # Abort Compilation
#======================================================================
# THE GRAMMAR
# <program> ::= { <id> ; <vars > <stmtlist> }
# <vars> ::= var { <id> ; } % DECLARATIONS
# <array> ::= [<expr>]
# <stmtlist> ::= <stmt> { ; <stmt> }
# <stmt> ::= print <id>
# <id> = <expr>
# <expr> ::= <factor> { (+ | -) <factor> } % No precedence
# <factor> ::= [+/-] ID | Number
#======================================================================
# Centralised Parser Error Message handler
#======================================================================
#===============================================================================
def error (msg):
#===============================================================================
print line
print "-" * charIndex,"^"
print("Error on %d - %s\n" % (number, msg))
printToken(token)
print("\n")
#===============================================================================
def emit (memadr, opcode, parameter):
#===============================================================================
"""EMIT CODE - Emit a of code with a Parameter
if first arg is zero - (the memory address), use and incr CODEPTR"""
global codeptr
if (memadr == 0):
memadr = codeptr
codeptr = codeptr+1
print "%6d %-8s %-7s" % (memadr, opcode, parameter)
#======================================================================
# VARIABLE DECLARATIONS
# <vars> ::= V { <id> ; }
#===============================================================================
def vars() :
#===============================================================================
global varptr;
getoken(); #skip VARSYM - already been recognised
while (token.token == idsym):
if token.address != 0:
print("%c already declared\n", token.name);
else:
symtbl[token.name].address = varptr;
varptr = varptr +1
getoken(); #skip past identifier
if token.token == semicolon: getoken() #skip ;
else: error("semicolon expected in declaration")
#======================================================================
# STMTLIST
# <stmtlist> ::= <stmt> { ; <stmt> }
#===============================================================================
def stmtList():
#===============================================================================
stmt()
while (token.token == semicolon):
getoken() #skip ;
stmt()
#======================================================================
# STMT
#===============================================================================
def stmt():
#===============================================================================
""" <stmt> ::= print <expression> | <id> = <expression> | if <expression> | while <expression>
"""
global codeptr
# thisStmtAdr = codeptr # Jump DEMO - not part of Stmt
if token.token == printsym:
printStmt()
elif token.token == idsym:
assignStmt()
elif token.token == assignsym:
getoken()
elif token.token == ifsym:
ifStmt()
elif token.token == elsesym:
elseStmt()
elif token.token == whilesym:
whileStmt()
elif token.token == readint:
readIntStmt()
elif token.token == readch:
readChStmt()
elif token.token == writeint:
writeIntStmt()
elif token.token == writech:
writeChStmt()
elif token.token == rightbrace:
print("\n#*** Compilation finished ***\n")
else:
error("Expected start of a statement")
# emit (0, "return", thisStmtAdr) # Jump DEMO
#===============================================================================
def printStmt():
#===============================================================================
""" <printStmt> ::= print <expression>"""
getoken() # skip "print"
expression() # on return, expr result (at runtime) will be in ACC
emit(0, "writeint", 0) # Memory address 0 is the ACC
if token.token == rightbrace:
print("#\n*** Compilation finished ***\n")
#===============================================================================
def assignStmt():
#===============================================================================
"""
<id> = <expression>
"""
whichidentifier = token # Remember which ID on Left
getoken() # Get token after identifier
if token.token == notequals: # skip # then read next line
srcfile.read()
getoken()
elif token.token == assignsym: #if the next token is =
expression()
elif token.token == idsym: factor()
elif token.token == jumpeq: print("#")
elif token.token == jumpne: print("#")
elif token.token == lessthanequal: print("")
elif token.token == greaterthanequal: print("")
else:
error("Expected = in assignment statement")
expression()
# Save result into LHS runtime address
#===============================================================================
def ifStmt():
#if-then-else
#===============================================================================
""" <ifStmt> ::= if <expression>"""
getoken() # skip "if"
emit(0, "compare",60)
expression()
stmt()
emit(0, "return",0)
#===============================================================================
def elseStmt():
#if-then-else
#===============================================================================
""" <elseStmt> ::= else <expression>"""
getoken()
emit(0, "store", 888)
stmt()
#===============================================================================
def whileStmt():
#===============================================================================
""" <whileStmt> ::= while (condition)statement"""
getoken() # skip "if"
emit(0, "compare",50)
expression()
stmt()
emit(0, "increment", 1)
emit(0, "jumpi", 14)
#===============================================================================
def readIntStmt():
#===============================================================================
getoken()
expression() # skip "if"
emit(0, "readint",999)
#===============================================================================
def readChStmt():
#===============================================================================
getoken() # skip "if"
emit(0, "readch",11)
#===============================================================================
def writeIntStmt():
#===============================================================================
getoken() # skip "if"
expression()
emit(0, "writeint",50)
#===============================================================================
def writeChStmt():
#===============================================================================
getoken() # skip "if"
emit(0, "writech",51)
#===============================================================================
def expression():
#===============================================================================
"""
Leaves result in ACC at runtime
Use addresses 999 & 998 as Temporary variables
<expression> ::= <factor> { (+ | - | * | /) <factor> }
"""
factor()
while token.token == plus or token.token == minus or token.token == mpy or token.token == div or token.token == lessthan or token.token == greaterthan or token.token == jumpeq or token.token == jumpne or token.token == lessthanequal or token.token == greaterthanequal:
op = token # remember +/-
getoken() # skip past +/-
emit(0, "store", 600+token.value) # Save current result
factor() # Evaluate next factor
#working
if op.token == plus: #+
emit(0, "add", 601)
emit(0, "store", 200)
elif op.token == minus: # - Subtract - have to swap operand order
emit(0, "subtract", 603) # Leaves result in Acc
emit(0, "store", 201)
elif op.token == mpy: #*
emit(0, "load", 999)
emit(0, "mpy", 998)
emit(0, "store", 203)
elif op.token == div: #/
emit(0, "load", 999)
emit(0, "div", 998)
emit(0, "store", 882)
elif op.token == remainder: #%
emit(0, "load", 999)
emit(0, "mod", 998)
emit(0, "store", 883)
#===============================================================================
def factor():
#===============================================================================
"""
# FACTOR() - leaves result in ACC at runtime
<factor> ::= (+|-) identifier | number
"""
#Numbers
if token.token == idsym:
emit(0, "load", token.address)
getoken()
elif token.token == number:
emit(0, "loadv", token.value)
getoken()
elif token.token == assignsym:getoken()
elif token.token == jumpeq:
print("#==")
elif token.token == jumpne:
print("#!=")
elif token.token == lessthanequal:
print("#<=")
elif token.token == greaterthanequal:
print("#<=")
elif token.token == semicolon: getoken()
else: error("Start of Factor expected")
#===============================================================================
def program():
#===============================================================================
""" # PROGRAM - Start production of the grammar
# <program> ::= { <id> ; <vars > <stmtlist> }
"""
if token.token == leftbrace: getoken()
else: error(" { expected")
if token.token == idsym: getoken()
else: error("Program name expected")
if token.token == semicolon: getoken()
else: error("Semicolon expected")
if token.token == varsym : vars()
stmtList()
if token.token == number:
factor()
elif token.token == idsym: factor()
elif token.token == rightbrace:
print("\n")
else: error(" } expected")
# Compiler main function
#======================================================================
def main():
#======================================================================
global line
global srcfile
global outfile
global charIndex
initSymTbl()
srcfile = open('variable_declar.txt', 'r')
line = srcfile.read() # readline
# for line in open('tiny.txt', 'r'):
# if not line.startswith("#"):
# debugScanner = False
charIndex = 0
debugScanner = False
if debugScanner: # Scanner Test Routine - Read a line and display the tokens
getoken()
while token.token is not None: # Skeleton for testing Scanner
printToken(token)
# outfile.write(token)
getoken()
srcfile.close()
sys.exit(1)
else:
getoken() # Parse Program according to the grammar
program() # Call start non-terminal handler
#===============================================================================
# Main Compiler starts here
#===============================================================================
print "#Microcompiler.py v0.2"
emit(0, "load", 0)
main()
#srcfile = open('tiny.txt', 'r')
#lexer = shlex.shlex(srcfile)
#for token in lexer:
# print repr(token)
#getoken()
| [
[
8,
0,
0.0045,
0.0075,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
8,
0,
0.0202,
0.018,
0,
0.66,
0.0233,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0314,
0.0015,
0,
0.66,
... | [
"'''\nCreated on Jun 23, 2014\n\n@author: Brian\n'''",
"\"\"\" Giovanni's MicroCompiler Demo\n\n<program> ::= { <id> ; <vars > <stmtlist> }\n<vars> ::= V { <id> ; } % DECLARATIONS\n\n<stmtlist> ::= <stmt> { ; <stmt> }\n<stmt> ::= P <id> | <id> ... |
""" Giovanni's MicroCompiler Demo
<program> ::= { <id> ; <vars > <stmtlist> }
<vars> ::= V { <id> ; } % DECLARATIONS
<stmtlist> ::= <stmt> { ; <stmt> }
<stmt> ::= P <id> | <id> = <expr>
<expr> ::= <factor> { (+ | -) <factor> } % No precedence
<factor> ::= (+|-) ID | Number
"""
import sys
import shlex
#===============================================================================
# # Lexical Analyser - the "Scanner" - Define the TokenTypes
#===============================================================================
tokenNames =\
[ "unknownToken", "idsym", "assignsym", "leftbrace", "rightbrace",
"varsym", "semicolon", "whilesym", "leftbracket", "rightbracket",
"printsym", "ifsym", "elsesym", "equals", "notequals", "lessthan", "greaterthan",
"readch", "readint", "writech", "writeint",
"number", "plus", "minus", "mpy", "div", "jumpne", "jumpeq","lessthanequal","greaterthanequal","remainder", "endfile"]
# define the tokens as variables
unknownToken, idsym, assignsym, leftbrace, rightbrace,\
varsym, semicolon, whilesym, leftbracket, rightbracket,\
printsym, ifsym, elsesym, equals, notequals, lessthan, greaterthan,\
readch, readint, writech, writeint,\
number, plus, minus, mpy, div, jumpne, jumpeq, lessthanequal, greaterthanequal,remainder, endfile = range(0, len(tokenNames))
#===============================================================================
class symbol:
#===============================================================================
name = None # String representation
token = None; # Corresponding token
address = 0; # For variables, their runtime address
value = None # on defined for numbers
def __init__(self, name, token, value = 0):
self.name = name
self.token = token
self.address = 0 # for identifiers, their address
self.value = value # for numbers, their value
symtbl = {}; # The Symbol Table, a dictionary of symbols indexed by name
#======================================================================
# GLOBALS for output of Lexical Analyser
# Set by each call to GeToken()
token = None; # A symbol
line = "\n" # the complex source file as a string
charIndex = 0 # the position in the source
linenumber= 0 # The current number
EOF = chr(0)
#======================================================================
# Run Time Code Generation Variables
varptr = 500 # Arbitrary base address of memory for variables
codeptr = 10 # Address to output next instruction (for code)
#===============================================================================
# Symbol Table Management Routines
#===============================================================================
#===============================================================================
def addToSymTbl (name, token):
#===============================================================================
symtbl[name] = symbol(name, token) # Add a new symbol to the dictionary
return symtbl[name]
#===============================================================================
def lookup (thisName):
#===============================================================================
"# Find a given identifier in the Symbol Table, Return the symtbl entry"
if symtbl.has_key(thisName): # thisName has been seen before
return symtbl[thisName] # return the symtbl entry
else: return None
#===============================================================================
def initSymTbl():
#===============================================================================
"# Initialise Symbol Table, and preload reserved words"
addToSymTbl('var', varsym) # VAR
addToSymTbl('while', whilesym) # WHILE
addToSymTbl('for', whilesym) # WHILE
addToSymTbl('print', printsym) # PRINT
addToSymTbl('if', ifsym) # IF
addToSymTbl('else', elsesym) # ELSE
addToSymTbl('readint', readint) #READINT
addToSymTbl('writeint', writeint) #READINT
addToSymTbl('readch', readch) #READINT
addToSymTbl('writech', writech) #READINT
# Now add symbols - NB only single character symbols are here
# multicharacter one like ">=" are still to do
addToSymTbl( '=', assignsym)
addToSymTbl( '#', notequals)
addToSymTbl( '<', lessthan) #jumplt
addToSymTbl( '>', greaterthan) #jumpgt
addToSymTbl( '{', leftbrace )
addToSymTbl( '}', rightbrace)
addToSymTbl( '(', leftbracket)
addToSymTbl( ')', rightbracket)
addToSymTbl( '+', plus )
addToSymTbl( '-', minus)
addToSymTbl( '*', mpy)
addToSymTbl( '/', div)
addToSymTbl( ';', semicolon)
addToSymTbl( '%', remainder)
addToSymTbl( EOF, endfile)
#multicharacter one like ">=" are still to do
addToSymTbl( '==', jumpeq)
addToSymTbl( '!=', jumpne)
addToSymTbl( '<=', lessthanequal) #jumplt
addToSymTbl( '>=', greaterthanequal) #jumpgt
#===============================================================================
# Scanner Diagnostics
#===============================================================================
def printToken(tok):
#===============================================================================
" - display the specified token."
if tok.token == idsym:
print "Token = %10s, %-10s adr = %3d" %\
(tokenNames[tok.token], tok.name, tok.address)
elif tok.token == number:
print "Token = %10s %d" % (tokenNames[tok.token], tok.value)
else:
print "Token = %10s" % tokenNames[tok.token]
#==============================?=================================================
def dumpSymTbl():
#===============================================================================
""" Dump all the tokens in the symboltable """
print(" *** Symbol Table ***")
for name in symtbl.keys(): # keys is a list of the names (printable form of tokens)
tok = symtbl[name]
if tok.token == idsym:
printToken(tok)
#===============================================================================
def getch():
#===============================================================================
global line
global charIndex
global linenumber
while True:
if charIndex < len(line): # See if used up current line
ch = line[charIndex] # if not, get character
charIndex = charIndex+1 # & move pointer for next time
else:
#line = srcfile.readline()
#if line == "": line = EOF
#if line == "#": line = notequals
print "--> ",
line = raw_input() +"\n" # read new line, adding \n so it's like f.readline()
charIndex = 0 # & reset character pointer
linenumber = linenumber + 1
continue
if ch == "\n":
ch = " " # A newline is a token separator
if ch == "?":
dumpSymTbl()
continue
return ch
#===============================================================================
def ungetch():
#===============================================================================
""" Unget the next character peeked at when building variables, numbers
and when distinguishing between >= and > ...
"""
global charIndex;
charIndex = charIndex-1;
#===============================================================================
def getoken():
#===============================================================================
""" GETOKEN - Put next token into the global TOKEN """
global token
ch = getch() # skip whitespace
while ch in ["\t", " ", "\n", "#"]:
ch = getch()
# If ch is alphabetic then this is start of reserved word or an identifier
if ch.isalpha(): # Letter therefore it's either identifier or reserved word
name = ""
while ch.isalpha() or ch.isdigit() or ch == "_":
name = name + ch
ch = getch()
ungetch() # let terminator be used next time
token = lookup(name) # See if token's known
if token is None: # if not
token = addToSymTbl(name, idsym) # add as 'idsym'-IDENTIFIER
return # we've set token.token to either id or tokentype of reserved word
#---------------------------------------------------------------------
# If it's numeric return TOKEN=number & token.value = binary value
elif ch.isdigit():
# In the real version, build number and don't forget to end with ungetch()
token = symbol(ch, number, value = int(ch)) # simplistic SINGLE DIGIT Ascii to Binary
return
#---------------------------------------------------------------------
# Single character tokens
elif ch in ["=", "#", "<", ">", "{", "}", "(", ")", "+" , "-", "*", "/", ";","%", "==", EOF]:
token = lookup(ch) # preloaded with appropriate token
else:
print "Unknown character -->%s<- decimal %d" % (ch,ord(ch))
sys.exit(1) # Abort Compilation
#======================================================================
# THE GRAMMAR
# <program> ::= { <id> ; <vars > <stmtlist> }
# <vars> ::= var { <id> ; } % DECLARATIONS
# <stmtlist> ::= <stmt> { ; <stmt> }
# <stmt> ::= print <id>
# <id> = <expr>
# <expr> ::= <factor> { (+ | -) <factor> } % No precedence
# <factor> ::= ID | Number
#======================================================================
# Centralised Parser Error Message handler
#======================================================================
#===============================================================================
def error (msg):
#===============================================================================
print line
print "-" * charIndex,"^"
print("Error on %d - %s\n" % (number, msg))
printToken(token)
print("\n")
#===============================================================================
def emit (memadr, opcode, parameter):
#===============================================================================
"""EMIT CODE - Emit a of code with a Parameter
if first arg is zero - (the memory address), use and incr CODEPTR"""
global codeptr
if (memadr == 0):
memadr = codeptr
codeptr = codeptr+1
print "%6d %-8s %-7s" % (memadr, opcode, parameter)
#======================================================================
# VARIABLE DECLARATIONS
# <vars> ::= V { <id> ; }
#===============================================================================
def vars() :
#===============================================================================
global varptr;
getoken(); #skip VARSYM - already been recognised
while (token.token == idsym):
if token.address != 0:
print("%c already declared\n", token.name);
else:
symtbl[token.name].address = varptr;
varptr = varptr +1
getoken(); #skip past identifier
if token.token == semicolon: getoken() #skip ;
else: error("semicolon expected in declaration")
#======================================================================
# STMTLIST
# <stmtlist> ::= <stmt> { ; <stmt> }
#===============================================================================
def stmtList():
#===============================================================================
stmt()
while (token.token == semicolon):
getoken() #skip ;
stmt()
#======================================================================
# STMT
#===============================================================================
def stmt():
#===============================================================================
""" <stmt> ::= print <expression> | <id> = <expression> | if <expression> | while <expression>
"""
global codeptr
# thisStmtAdr = codeptr # Jump DEMO - not part of Stmt
if token.token == printsym:
printStmt()
elif token.token == idsym:
assignStmt()
elif token.token == ifsym:
ifStmt()
elif token.token == elsesym:
elseStmt()
elif token.token == whilesym:
whileStmt()
elif token.token == readint:
readIntStmt()
elif token.token == readch:
readChStmt()
elif token.token == writeint:
writeIntStmt()
elif token.token == writech:
writeChStmt()
elif token.token == rightbrace:
print("")
else:
error("Expected start of a statement")
# emit (0, "return", thisStmtAdr) # Jump DEMO
#===============================================================================
def printStmt():
#===============================================================================
""" <printStmt> ::= print <expression>"""
getoken() # skip "print"
expression() # on return, expr result (at runtime) will be in ACC
emit(0, "writeint", 202) # Memory address 0 is the ACC
if token.token == rightbrace:
print("\n#*** Compilation finished ***\n")
#===============================================================================
def assignStmt():
#===============================================================================
"""
<id> = <expression>
"""
whichidentifier = token # Remember which ID on Left
getoken() # Get token after identifier
if token.token == assignsym:
getoken()
elif token.token == jumpeq:
getoken()
else:
error("Expected = in assignment statement")
expression()
# Save result into LHS runtime address
#===============================================================================
def ifStmt():
#if-then-else
#===============================================================================
""" <ifStmt> ::= if <expression>"""
getoken() # skip "if"
emit(0, "compare",60)
expression()
stmt()
emit(0, "return",0)
#===============================================================================
def elseStmt():
#if-then-else
#===============================================================================
""" <elseStmt> ::= else <expression>"""
getoken()
emit(0, "store", 888)
stmt()
#===============================================================================
def whileStmt():
#===============================================================================
""" <whileStmt> ::= while (condition)statement"""
getoken() # skip "if"
emit(0, "compare",50)
expression()
stmt()
emit(0, "increment", 1)
emit(0, "jumpi", 14)
#===============================================================================
def readIntStmt():
#===============================================================================
getoken()
expression() # skip "if"
emit(0, "readint",999)
#===============================================================================
def readChStmt():
#===============================================================================
getoken() # skip "if"
emit(0, "readch",11)
#===============================================================================
def writeIntStmt():
#===============================================================================
getoken() # skip "if"
expression()
emit(0, "writeint",202)
#===============================================================================
def writeChStmt():
#===============================================================================
getoken() # skip "if"
emit(0, "writech",51)
#===============================================================================
def expression():
#===============================================================================
"""
Leaves result in ACC at runtime
Use addresses 999 & 998 as Temporary variables
<expression> ::= <factor> { (+ | - | * | /) <factor> }
"""
#1st number
factor()
while token.token == plus or token.token == minus or token.token == mpy or token.token == div or token.token == remainder:
op = token # remember +/-
getoken() # skip past +/-
if token.token == leftbracket:getoken()
factor()
if token.token == plus:
getoken()
emit(0, "loadv", token.value)
emit(0, "add", 103)
emit(0, "store", 200)
getoken()
if op.token == mpy:
getoken()
emit(0, "mpy", 104)
emit(0, "store", 201)
if token.token == rightbracket:getoken()
if op.token == plus:
emit(0, "loadv", 999)
emit(0, "add", 999)
emit(0, "store", 5)
elif op.token == minus: # Subtract - have to swap operand order
emit(0, "store", 998)
emit(0, "load" , 999)
emit(0, "subtract", 998) # Leaves result in Acc
emit(0, "store", 6)
if token.token == semicolon: getoken()
elif op.token == div:
emit(0, "div", 102)
emit(0, "store", 202)
getoken()
elif op.token == remainder: #%
emit(0, "store", 998)
emit(0, "load", 999)
emit(0, "mod", 998)
emit(0, "store", 883)
#===============================================================================
def factor():
#===============================================================================
"""
# FACTOR() - leaves result in ACC at runtime
<factor> ::= (+|-) identifier | number
"""
#Numbers
if token.token == idsym:
emit(0, "load", token.address)
getoken()
elif token.token == number:
emit(0, "loadv", token.value)
emit(0, "store", token.value+100)
getoken()
else: error("Start of Factor expected")
#===============================================================================
def program():
#===============================================================================
""" # PROGRAM - Start production of the grammar
# <program> ::= { <id> ; <vars > <stmtlist> }
"""
if token.token == leftbrace: getoken()
else: error(" { expected")
if token.token == idsym: getoken()
else: error("Program name expected")
if token.token == semicolon: getoken()
else: error("Semicolon expected")
if token.token == varsym : vars()
stmtList()
if token.token == printsym: printStmt()
if token.token == semicolon: getoken()
else: error("Semicolon expected")
if token.token == rightbrace:
print("\n#*** Compilation finished ***\n")
else: error(" } expected")
# Compiler main function
#======================================================================
def main():
#======================================================================
global line
global srcfile
global outfile
global charIndex
initSymTbl()
srcfile = open('complex_expression.txt', 'r')
line = srcfile.read() # readline
# for line in open('tiny.txt', 'r'):
# if not line.startswith("#"):
# debugScanner = False
charIndex = 0
debugScanner = False
if debugScanner: # Scanner Test Routine - Read a line and display the tokens
getoken()
while token.token is not None: # Skeleton for testing Scanner
printToken(token)
getoken()
sys.exit(1)
# writefile.close()
else:
getoken() # Parse Program according to the grammar
program() # Call start non-terminal handler
#===============================================================================
# Main Compiler starts here
#===============================================================================
writefile = open('test.txt', 'w')
writefile.write("#Microcompiler.py v0.2")
writefile.close()
"""emit(0, "load", 0)
emit(0, "constant", "'A'")
emit(0, "constant", 10)
emit(0, "constant", 12)
emit(0, "constant", 25)
emit(0, "constant", -10)
"""
emit(0, "load", 0)
main()
srcfile = open('complex_expression.txt', 'r')
lexer = shlex.shlex(srcfile)
for token in lexer:
print "#" + repr(token)
#getoken()
| [
[
8,
0,
0.0142,
0.0201,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0268,
0.0017,
0,
0.66,
0.0208,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.0285,
0.0017,
0,
0.66... | [
"\"\"\" Giovanni's MicroCompiler Demo\n\n<program> ::= { <id> ; <vars > <stmtlist> }\n<vars> ::= V { <id> ; } % DECLARATIONS\n\n<stmtlist> ::= <stmt> { ; <stmt> }\n<stmt> ::= P <id> | <id> = <expr>",
"import sys",
"import shlex",
"tokenName... |
""" Giovanni's MicroCompiler Demo
<program> ::= { <id> ; <vars > <stmtlist> }
<vars> ::= V { <id> ; } % DECLARATIONS
<stmtlist> ::= <stmt> { ; <stmt> }
<stmt> ::= P <id> | <id> = <expr>
<expr> ::= <factor> { (+ | -) <factor> } % No precedence
<factor> ::= (+|-) ID | Number
"""
import sys
import shlex
#===============================================================================
# # Lexical Analyser - the "Scanner" - Define the TokenTypes
#===============================================================================
tokenNames =\
[ "unknownToken", "idsym", "assignsym", "leftbrace", "rightbrace",
"varsym", "semicolon", "whilesym", "leftbracket", "rightbracket","leftparen","rightparen",
"printsym", "ifsym", "elsesym", "equals", "notequals", "lessthan", "greaterthan",
"readch", "readint", "writech", "writeint","comma","dot","appendsym",
"number", "plus", "minus", "mpy", "div", "jumpne", "jumpeq","lessthanequal","greaterthanequal", "endfile"]
# define the tokens as variables
unknownToken, idsym, assignsym, leftbrace, rightbrace,\
varsym, semicolon, whilesym, leftbracket, rightbracket, leftparen, rightparen,\
printsym, ifsym, elsesym, equals, notequals, lessthan, greaterthan,\
readch, readint, writech, writeint,comma,dot,appendsym,\
number, plus, minus, mpy, div, jumpne, jumpeq, lessthanequal, greaterthanequal, endfile = range(0, len(tokenNames))
#===============================================================================
class symbol:
#===============================================================================
name = None # String representation
token = None; # Corresponding token
address = 0; # For variables, their runtime address
value = None # on defined for numbers
def __init__(self, name, token, value = 0):
self.name = name
self.token = token
self.address = 0 # for identifiers, their address
self.value = value # for numbers, their value
symtbl = {}; # The Symbol Table, a dictionary of symbols indexed by name
#======================================================================
# GLOBALS for output of Lexical Analyser
# Set by each call to GeToken()
token = None; # A symbol
line = "\n" # the complex source file as a string
charIndex = 0 # the position in the source
linenumber= 0 # The current number
EOF = chr(0)
#======================================================================
# Run Time Code Generation Variables
varptr = 500 # Arbitrary base address of memory for variables
codeptr = 10 # Address to output next instruction (for code)
#===============================================================================
# Symbol Table Management Routines
#===============================================================================
#===============================================================================
def addToSymTbl (name, token):
#===============================================================================
symtbl[name] = symbol(name, token) # Add a new symbol to the dictionary
return symtbl[name]
#===============================================================================
def lookup (thisName):
#===============================================================================
"# Find a given identifier in the Symbol Table, Return the symtbl entry"
if symtbl.has_key(thisName): # thisName has been seen before
return symtbl[thisName] # return the symtbl entry
else: return None
#===============================================================================
def initSymTbl():
#===============================================================================
"# Initialise Symbol Table, and preload reserved words"
addToSymTbl('var', varsym) # VAR
addToSymTbl('while', whilesym) # WHILE
addToSymTbl('for', whilesym) # WHILE
addToSymTbl('print', printsym) # PRINT
addToSymTbl('append', appendsym)
addToSymTbl('if', ifsym) # IF
addToSymTbl('else', elsesym) # ELSE
addToSymTbl('readint', readint) #READINT
addToSymTbl('writeint', writeint) #READINT
addToSymTbl('readch', readch) #READINT
addToSymTbl('writech', writech) #READINT
# Now add symbols - NB only single character symbols are here
# multicharacter one like ">=" are still to do
addToSymTbl( '=', assignsym)
addToSymTbl( '#', notequals)
addToSymTbl( '<', lessthan) #jumplt
addToSymTbl( '>', greaterthan) #jumpgt
addToSymTbl( '{', leftbrace )
addToSymTbl( '}', rightbrace)
addToSymTbl( '(', leftbracket)
addToSymTbl( ')', rightbracket)
addToSymTbl( '[', leftparen)
addToSymTbl( ']', rightparen)
addToSymTbl( '+', plus )
addToSymTbl( '-', minus)
addToSymTbl( '*', mpy)
addToSymTbl( '/', div)
addToSymTbl( ';', semicolon)
addToSymTbl( EOF, endfile)
addToSymTbl( ',', comma)
addToSymTbl( '.', dot)
#multicharacter one like ">=" are still to do
addToSymTbl( '==', jumpeq)
addToSymTbl( '!=', jumpne)
addToSymTbl( '<=', lessthanequal) #jumplt
addToSymTbl( '>=', greaterthanequal) #jumpgt
#===============================================================================
# Scanner Diagnostics
#===============================================================================
def printToken(tok):
#===============================================================================
" - display the specified token."
if tok.token == idsym:
print "Token = %10s, %-10s adr = %3d" %\
(tokenNames[tok.token], tok.name, tok.address)
elif tok.token == number:
print "Token = %10s %d" % (tokenNames[tok.token], tok.value)
else:
print "Token = %10s" % tokenNames[tok.token]
#==============================?=================================================
def dumpSymTbl():
#===============================================================================
""" Dump all the tokens in the symboltable """
print(" *** Symbol Table ***")
for name in symtbl.keys(): # keys is a list of the names (printable form of tokens)
tok = symtbl[name]
if tok.token == idsym:
printToken(tok)
#===============================================================================
def getch():
#===============================================================================
global line
global charIndex
global linenumber
while True:
if charIndex < len(line): # See if used up current line
ch = line[charIndex] # if not, get character
charIndex = charIndex+1 # & move pointer for next time
else:
#line = srcfile.readline()
if line == "": line = EOF
##print "--> ",
line = raw_input() +"\n" # read new line, adding \n so it's like f.readline()
charIndex = 0 # & reset character pointer
linenumber = linenumber + 1
continue
if ch == "\n":
ch = " " # A newline is a token separator
if ch == "?":
dumpSymTbl()
continue
return ch
#===============================================================================
def ungetch():
#===============================================================================
""" Unget the next character peeked at when building variables, numbers
and when distinguishing between >= and > ...
"""
global charIndex;
charIndex = charIndex-1;
#===============================================================================
def getoken():
#===============================================================================
""" GETOKEN - Put next token into the global TOKEN """
global token
ch = getch() # skip whitespace
while ch in ["\t", " ", "\n", "#"]:
ch = getch()
# If ch is alphabetic then this is start of reserved word or an identifier
if ch.isalpha(): # Letter therefore it's either identifier or reserved word
name = ""
while ch.isalpha() or ch.isdigit() or ch == "_":
name = name + ch
ch = getch()
ungetch() # let terminator be used next time
token = lookup(name) # See if token's known
if token is None: # if not
token = addToSymTbl(name, idsym) # add as 'idsym'-IDENTIFIER
return # we've set token.token to either id or tokentype of reserved word
#---------------------------------------------------------------------
# If it's numeric return TOKEN=number & token.value = binary value
elif ch.isdigit():
# In the real version, build number and don't forget to end with ungetch()
token = symbol(ch, number, value = int(ch)) # simplistic SINGLE DIGIT Ascii to Binary
return
#---------------------------------------------------------------------
# Single character tokens
elif ch in ["=", "#", "<", ">", "{", "}", "(", ")", "[","]", "+" , "-", "*", "/", ";","!", "==",",",".", EOF]:
token = lookup(ch) # preloaded with appropriate token
else:
print "Unknown character -->%s<- decimal %d" % (ch,ord(ch))
sys.exit(1) # Abort Compilation
#======================================================================
# THE GRAMMAR
# <program> ::= { <id> ; <vars > <stmtlist> }
# <vars> ::= var { <id> ; } % DECLARATIONS
# <array> ::= [<expr>]
# <stmtlist> ::= <stmt> { ; <stmt> }
# <stmt> ::= print <id>
# <id> = <expr>
# <expr> ::= <factor> { (+ | - | * | /) <factor> } % No precedence
# <factor> ::= [+/-] ID | Number
#======================================================================
# Centralised Parser Error Message handler
#======================================================================
#===============================================================================
def error (msg):
#===============================================================================
print line
print "-" * charIndex,"^"
print("Error on %d - %s\n" % (number, msg))
printToken(token)
print("\n")
#===============================================================================
def emit (memadr, opcode, parameter):
#===============================================================================
"""EMIT CODE - Emit a of code with a Parameter
if first arg is zero - (the memory address), use and incr CODEPTR"""
global codeptr
if (memadr == 0):
memadr = codeptr
codeptr = codeptr+1
print "%6d %-8s %-7s" % (memadr, opcode, parameter)
#======================================================================
# VARIABLE DECLARATIONS
# <vars> ::= V { <id> ; }
#===============================================================================
def vars() :
#===============================================================================
global varptr;
getoken(); #skip VARSYM - already been recognised
while (token.token == idsym):
if token.address != 0:
print("%c already declared\n", token.name);
else:
symtbl[token.name].address = varptr;
varptr = varptr +1
getoken(); #skip past identifier
if token.token == assignsym:assignStmt()
if token.token == semicolon: getoken() #skip ;
else: error("semicolon expected in declaration")
#===============================================================================
def array():
#a=[1,2,3];
#a=append(4);
#print a;
#===============================================================================
global array;
global list;
list =[];
#a=[1,2,3];
while (token.token == number):
print("#array address")
emit(0, "loadv", token.value)
list.append(token.value)
emit(0, "store", token.value+100)
emit(0, "push", token.value+200)
getoken()
if token.token == comma:getoken()
if token.token == rightparen:getoken()
if token.token == semicolon:getoken()
print ("\n"+ "#This is a list of array from txt\n" + "#"+str(list) + "\n");
if token.token == idsym:getoken()
if token.token == dot:getoken()
if token.token == appendsym:getoken()
if token.token == leftbracket:getoken()
while( token.token == number):
print("#store new value to list")
emit(0, "load", token.value)
list.append(token.value)
emit(0, "store", 104)
emit(0, "push", token.value+200)
getoken()
print("\n"+ "#Now the list have new value added to list" + "\n#"+str(list)+"\n")
if token.token == rightbracket:getoken()
if token.token == semicolon:getoken()
#======================================================================
# STMTLIST
# <stmtlist> ::= <stmt> { ; <stmt> }
#===============================================================================
def stmtList():
#===============================================================================
stmt()
while (token.token == semicolon):
getoken() #skip ;
stmt()
#======================================================================
# STMT
#===============================================================================
def stmt():
#===============================================================================
""" <stmt> ::= print <expression> | <id> = <expression> | if <expression> | while <expression>
"""
global codeptr
thisStmtAdr = codeptr # Jump DEMO - not part of Stmt
if token.token == printsym:
printStmt()
if token.token == varsym:
vars()
elif token.token == idsym:
assignStmt()
elif token.token == rightbrace:
print("\n#*** Compilation finished ***\n")
else:
error("Expected start of a statement")
# emit (0, "return", thisStmtAdr) # Jump DEMO
#===============================================================================
def printStmt():
#===============================================================================
""" <printStmt> ::= print <expression>"""
getoken() # skip "print"
if token.token == idsym: getoken()
if token.token == leftparen:getoken()
if token.token == number:
searchindex = token.value
print("\n#The search index is " + str(searchindex))
print ("#The value got from list is " + str(list[searchindex]))
emit(0, "loadv", list[searchindex])
emit(0, "store", 206)
print("\n")
getoken()
if token.token == rightparen:getoken()
if token.token == plus:
getoken()
emit(0, "loadv", token.value)
emit(0, "add", 206)
emit(0, "store", 101)
emit(0, "writeint", 0) # Memory address 0 is the ACC
getoken()
if token.token == semicolon: getoken()
print("#The result of a[1]+5 should be 7")
if token.token == rightbrace:
print("")
#===============================================================================
def assignStmt():
#===============================================================================
"""
<id> = <expression>
"""
whichidentifier = token # Remember which ID on Left
getoken() # Get token after identifier
if token.token == notequals:
srcfile.read()
# getoken()
elif token.token == assignsym:
getoken()
elif token.token == number:
factor()
elif token.token == leftparen: # [
array()
else:
error("Expected = in assignment statement")
expression()
# Save result into LHS runtime address
#===============================================================================
def expression():
#===============================================================================
"""
Leaves result in ACC at runtime
Use addresses 999 & 998 as Temporary variables
<expression> ::= <factor> { (+ | - | * | /) <factor> }
"""
factor()
while token.token == plus or token.token == jumpeq:
op = token # remember +/-
getoken() # skip past +/-
emit(0, "store", 999) # Save current result
if token.token == jumpeq:
emit(0, "store", 998)
emit(0, "compare", 999)
emit(0, "jumpeq", 83)
#===============================================================================
def factor():
#===============================================================================
"""
# FACTOR() - leaves result in ACC at runtime
<factor> ::= (+|-) identifier | number
"""
#Numbers
if token.token == idsym:
emit(0, "load", token.address)
getoken()
elif token.token == number:
print("# Store value")
emit(0, "loadv", token.value)
emit(0, "store", 50)
print(" ")
getoken()
elif token.token == leftparen:getoken()
elif token.token == assignsym:getoken()
elif token.token == semicolon:getoken()
else: error("Start of Factor expected")
#===============================================================================
def program():
#===============================================================================
""" # PROGRAM - Start production of the grammar
# <program> ::= { <id> ; <vars > <stmtlist> }
"""
global searchindex;
global result;
if token.token == leftbrace: getoken()
else: error(" { expected")
if token.token == idsym: getoken()
else: error("Program name expected")
if token.token == semicolon: getoken()
else: error("Semicolon expected")
stmtList()
if token.token == rightparen: getoken()
elif token.token == number: array()
# else: error(" ] expected")
if token.token == printsym:printStmt()
stmtList()
getoken()
if token.token == rightbrace:
print("\n#*** Compilation finished ***\n")
else: error(" } expected")
# Compiler main function
#======================================================================
def main():
#======================================================================
global line
global srcfile
global outfile
global charIndex
initSymTbl()
srcfile = open('declare_array.txt', 'r')
line = srcfile.read() # readline
charIndex = 0
debugScanner = False
if debugScanner: # Scanner Test Routine - Read a line and display the tokens
getoken()
while token.token is not None: # Skeleton for testing Scanner
printToken(token)
# outfile.write(token)
getoken()
srcfile.close()
sys.exit(1)
else:
getoken() # Parse Program according to the grammar
program() # Call start non-terminal handler
#===============================================================================
# Main Compiler starts here
#===============================================================================
print "#Microcompiler.py v0.2"
emit(0, "load", 0)
#emit(0, "constant", "'A'")
#emit(0, "constant", 10)
#emit(0, "constant", 8)
#emit(0, "constant", 25)
#emit(0, "constant", -10)
main()
"""srcfile = open('tiny.txt', 'r')
lexer = shlex.shlex(srcfile)
for token in lexer:
print repr(token)
"""
#getoken()
| [
[
8,
0,
0.0144,
0.0204,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0272,
0.0017,
0,
0.66,
0.027,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.0289,
0.0017,
0,
0.66,... | [
"\"\"\" Giovanni's MicroCompiler Demo\n\n<program> ::= { <id> ; <vars > <stmtlist> }\n<vars> ::= V { <id> ; } % DECLARATIONS\n\n<stmtlist> ::= <stmt> { ; <stmt> }\n<stmt> ::= P <id> | <id> = <expr>",
"import sys",
"import shlex",
"tokenName... |
""" Giovanni's MicroCompiler Demo
<program> ::= { <id> ; <vars > <stmtlist> }
<vars> ::= V { <id> ; } % DECLARATIONS
<stmtlist> ::= <stmt> { ; <stmt> }
<stmt> ::= P <id> | <id> = <expr>
<expr> ::= <factor> { (+ | -) <factor> } % No precedence
<factor> ::= (+|-) ID | Number
"""
import sys
import shlex
#===============================================================================
# # Lexical Analyser - the "Scanner" - Define the TokenTypes
#===============================================================================
tokenNames =\
[ "unknownToken", "idsym", "assignsym", "leftbrace", "rightbrace",
"varsym", "semicolon", "whilesym", "leftbracket", "rightbracket",
"printsym", "ifsym", "elsesym", "equals", "notequals", "lessthan", "greaterthan",
"readch", "readint", "writech", "writeint", "halt",
"number", "plus", "minus", "mpy", "div", "jumpne", "jumpeq","lessthanequal","greaterthanequal", "endfile"]
# define the tokens as variables
unknownToken, idsym, assignsym, leftbrace, rightbrace,\
varsym, semicolon, whilesym, leftbracket, rightbracket,\
printsym, ifsym, elsesym, equals, notequals, lessthan, greaterthan,\
readch, readint, writech, writeint, halt,\
number, plus, minus, mpy, div, jumpne, jumpeq, lessthanequal, greaterthanequal, endfile = range(0, len(tokenNames))
#===============================================================================
class symbol:
#===============================================================================
name = None # String representation
token = None; # Corresponding token
address = 0; # For variables, their runtime address
value = None # on defined for numbers
def __init__(self, name, token, value = 0):
self.name = name
self.token = token
self.address = 0 # for identifiers, their address
self.value = value # for numbers, their value
symtbl = {}; # The Symbol Table, a dictionary of symbols indexed by name
#======================================================================
# GLOBALS for output of Lexical Analyser
# Set by each call to GeToken()
token = None; # A symbol
line = "\n" # the complex source file as a string
charIndex = 0 # the position in the source
linenumber= 0 # The current number
EOF = chr(0)
#======================================================================
# Run Time Code Generation Variables
varptr = 500 # Arbitrary base address of memory for variables
codeptr = 10 # Address to output next instruction (for code)
#===============================================================================
# Symbol Table Management Routines
#===============================================================================
#===============================================================================
def addToSymTbl (name, token):
#===============================================================================
symtbl[name] = symbol(name, token) # Add a new symbol to the dictionary
return symtbl[name]
#===============================================================================
def lookup (thisName):
#===============================================================================
"# Find a given identifier in the Symbol Table, Return the symtbl entry"
if symtbl.has_key(thisName): # thisName has been seen before
return symtbl[thisName] # return the symtbl entry
else: return None
#===============================================================================
def initSymTbl():
#===============================================================================
"# Initialise Symbol Table, and preload reserved words"
addToSymTbl('var', varsym) # VAR
addToSymTbl('while', whilesym) # WHILE
addToSymTbl('for', whilesym) # WHILE
addToSymTbl('print', printsym) # PRINT
addToSymTbl('if', ifsym) # IF
addToSymTbl('else', elsesym) # ELSE
addToSymTbl('readint', readint) #READINT
addToSymTbl('writeint', writeint) #READINT
addToSymTbl('readch', readch) #READINT
addToSymTbl('writech', writech) #READINT
addToSymTbl('halt', halt)
# Now add symbols - NB only single character symbols are here
# multicharacter one like ">=" are still to do
addToSymTbl( '=', assignsym)
addToSymTbl( '#', notequals)
addToSymTbl( '<', lessthan) #jumplt
addToSymTbl( '>', greaterthan) #jumpgt
addToSymTbl( '{', leftbrace )
addToSymTbl( '}', rightbrace)
addToSymTbl( '(', leftbracket)
addToSymTbl( ')', rightbracket)
addToSymTbl( '+', plus )
addToSymTbl( '-', minus)
addToSymTbl( '*', mpy)
addToSymTbl( '/', div)
addToSymTbl( ';', semicolon)
addToSymTbl( EOF, endfile)
#multicharacter one like ">=" are still to do
addToSymTbl( '==', jumpeq)
addToSymTbl( '!=', jumpne)
addToSymTbl( '<=', lessthanequal) #jumplt
addToSymTbl( '>=', greaterthanequal) #jumpgt
#===============================================================================
# Scanner Diagnostics
#===============================================================================
def printToken(tok):
#===============================================================================
" - display the specified token."
if tok.token == idsym:
print "Token = %10s, %-10s adr = %3d" %\
(tokenNames[tok.token], tok.name, tok.address)
elif tok.token == number:
print "Token = %10s %d" % (tokenNames[tok.token], tok.value)
else:
print "Token = %10s" % tokenNames[tok.token]
#==============================?=================================================
def dumpSymTbl():
#===============================================================================
""" Dump all the tokens in the symboltable """
print(" *** Symbol Table ***")
for name in symtbl.keys(): # keys is a list of the names (printable form of tokens)
tok = symtbl[name]
if tok.token == idsym:
printToken(tok)
#===============================================================================
def getch():
#===============================================================================
global line
global charIndex
global linenumber
while True:
if charIndex < len(line): # See if used up current line
ch = line[charIndex] # if not, get character
charIndex = charIndex+1 # & move pointer for next time
else:
#line = srcfile.readline()
#if line == "": line = EOF
#if line == "#": line = notequals
print "--> ",
line = raw_input() +"\n" # read new line, adding \n so it's like f.readline()
charIndex = 0 # & reset character pointer
linenumber = linenumber + 1
continue
if ch == "\n":
ch = " " # A newline is a token separator
if ch == "?":
dumpSymTbl()
continue
return ch
#===============================================================================
def ungetch():
#===============================================================================
""" Unget the next character peeked at when building variables, numbers
and when distinguishing between >= and > ...
"""
global charIndex;
charIndex = charIndex-1;
#===============================================================================
def getoken():
#===============================================================================
""" GETOKEN - Put next token into the global TOKEN """
global token
ch = getch() # skip whitespace
while ch in ["\t", " ", "\n", "#"]:
ch = getch()
# If ch is alphabetic then this is start of reserved word or an identifier
if ch.isalpha(): # Letter therefore it's either identifier or reserved word
name = ""
while ch.isalpha() or ch.isdigit() or ch == "_":
name = name + ch
ch = getch()
ungetch() # let terminator be used next time
token = lookup(name) # See if token's known
if token is None: # if not
token = addToSymTbl(name, idsym) # add as 'idsym'-IDENTIFIER
return # we've set token.token to either id or tokentype of reserved word
#---------------------------------------------------------------------
# If it's numeric return TOKEN=number & token.value = binary value
elif ch.isdigit():
# In the real version, build number and don't forget to end with ungetch()
token = symbol(ch, number, value = int(ch)) # simplistic SINGLE DIGIT Ascii to Binary
return
#---------------------------------------------------------------------
# Single character tokens
elif ch in ["=", "#", "<", ">", "{", "}", "(", ")", "+" , "-", "*", "/", ";","!", "==", EOF]:
token = lookup(ch) # preloaded with appropriate token
else:
print "Unknown character -->%s<- decimal %d" % (ch,ord(ch))
sys.exit(1) # Abort Compilation
#======================================================================
# THE GRAMMAR
# <program> ::= { <id> ; <vars > <stmtlist> }
# <vars> ::= var { <id> ; } % DECLARATIONS
# <stmtlist> ::= <stmt> { ; <stmt> }
# <stmt> ::= print <id>
# <id> = <expr>
# <expr> ::= <factor> { (+ | -) <factor> } % No precedence
# <factor> ::= ID | Number
#======================================================================
# Centralised Parser Error Message handler
#======================================================================
#===============================================================================
def error (msg):
#===============================================================================
print line
print "-" * charIndex,"^"
print("Error on %d - %s\n" % (number, msg))
printToken(token)
print("\n")
#===============================================================================
def emit (memadr, opcode, parameter):
#===============================================================================
"""EMIT CODE - Emit a of code with a Parameter
if first arg is zero - (the memory address), use and incr CODEPTR"""
global codeptr
if (memadr == 0):
memadr = codeptr
codeptr = codeptr+1
print "%6d %-8s %-7s" % (memadr, opcode, parameter)
#======================================================================
# VARIABLE DECLARATIONS
# <vars> ::= V { <id> ; }
#===============================================================================
def vars() :
#===============================================================================
global varptr;
getoken(); #skip VARSYM - already been recognised
while (token.token == idsym):
if token.address != 0:
print("%c already declared\n", token.name);
else:
symtbl[token.name].address = varptr;
varptr = varptr +1
getoken(); #skip past identifier
if token.token == semicolon: getoken() #skip ;
else: error("semicolon expected in declaration")
#======================================================================
# STMTLIST
# <stmtlist> ::= <stmt> { ; <stmt> }
#===============================================================================
def stmtList():
#===============================================================================
stmt()
while (token.token == semicolon):
getoken() #skip ;
stmt()
#======================================================================
# STMT
#===============================================================================
def stmt():
#===============================================================================
""" <stmt> ::= print <expression> | <id> = <expression> | if <expression> | while <expression>
"""
global codeptr
# thisStmtAdr = codeptr # Jump DEMO - not part of Stmt
if token.token == printsym:
printStmt()
elif token.token == idsym:
assignStmt()
elif token.token == halt:
emit(0, "halt",0 )
elif token.token == ifsym:
ifStmt()
elif token.token == elsesym:
elseStmt()
elif token.token == whilesym:
whileStmt()
elif token.token == readint:
readIntStmt()
elif token.token == readch:
readChStmt()
elif token.token == writeint:
writeIntStmt()
elif token.token == writech:
writeChStmt()
elif token.token == rightbrace:
print("\n#*** Compilation finished ***\n")
else:
error("Expected start of a statement")
# emit (0, "return", thisStmtAdr) # Jump DEMO
#===============================================================================
def printStmt():
#===============================================================================
""" <printStmt> ::= print <expression>"""
getoken() # skip "print"
expression() # on return, expr result (at runtime) will be in ACC
emit(0, "writeint", 0) # Memory address 0 is the ACC
if token.token == rightbrace:
print("\n#*** Compilation finished ***\n")
#===============================================================================
def assignStmt():
#===============================================================================
"""
<id> = <expression>
"""
whichidentifier = token # Remember which ID on Left
getoken() # Get token after identifier
if token.token == assignsym:
getoken()
elif token.token == jumpeq:
getoken()
else:
error("Expected = in assignment statement")
expression()
# Save result into LHS runtime address
#===============================================================================
def ifStmt():
#if-then-else
#===============================================================================
""" <ifStmt> ::= if <expression>"""
getoken() # skip "if"
emit(0, "compare",60)
expression()
stmt()
emit(0, "return",0)
#===============================================================================
def elseStmt():
#if-then-else
#===============================================================================
""" <elseStmt> ::= else <expression>"""
getoken()
emit(0, "store", 888)
stmt()
#===============================================================================
def whileStmt():
#===============================================================================
""" <whileStmt> ::= while (condition)statement"""
getoken() # skip "if"
emit(0, "compare",50)
expression()
stmt()
emit(0, "increment", 1)
emit(0, "jumpi", 14)
#===============================================================================
def readIntStmt():
#===============================================================================
getoken()
expression() # skip "if"
emit(0, "readint",999)
#===============================================================================
def readChStmt():
#===============================================================================
getoken() # skip "if"
emit(0, "readch",11)
#===============================================================================
def writeIntStmt():
#===============================================================================
getoken() # skip "if"
expression()
emit(0, "writeint",50)
#===============================================================================
def writeChStmt():
#===============================================================================
getoken() # skip "if"
emit(0, "writech",51)
#===============================================================================
def expression():
#===============================================================================
"""
Leaves result in ACC at runtime
Use addresses 999 & 998 as Temporary variables
<expression> ::= <factor> { (+ | - | * | /) <factor> }
"""
factor()
while token.token == plus or token.token == minus or token.token == mpy or token.token == div or token.token == lessthan or token.token == greaterthan or token.token == jumpne or token.token == jumpeq:
op = token # remember +/-
getoken() # skip past +/-
emit(0, "store", 999) # Save current result
factor() # Evaluate next factor
#working
if op.token == plus:
emit(0, "loadv", 999)
emit(0, "add", 999)
emit(0, "store", 999)
if op.token == leftbracket:getoken()
elif op.token == minus: # Subtract - have to swap operand order
emit(0, "store", 998)
emit(0, "load" , 999)
emit(0, "subtract", 998) # Leaves result in Acc
emit(0, "store", 6)
elif op.token == mpy:
emit(0, "store", 998)
emit(0, "load", 999)
emit(0, "mpy", 998)
emit(0, "store", 7)
elif op.token == div:
emit(0, "store", 998)
emit(0, "load", 999)
emit(0, "div", 998)
emit(0, "store", 8)
elif op.token == lessthan:
emit(0, "store", 998)
emit(0, "compare", 999)
emit(0, "jumplt", 80)
emit(0, "loadv", 0)
emit(0, "store", 9)
elif op.token == greaterthan:
emit(0, "store", 998)
emit(0, "compare", 999)
emit(0, "jumpgt", 81)
emit(0, "loadv", 0)
emit(0, "store", 10)
#not working
elif op.token == jumpne:
emit(0, "store", 998)
emit(0, "compare", 999)
emit(0, "jumpne", 82)
emit(0, "loadv", 0)
emit(0, "store", 11)
elif op.token == jumpeq:
emit(0, "store", 998)
emit(0, "compare", 999)
emit(0, "jumpeq", 83)
#===============================================================================
def factor():
#===============================================================================
"""
# FACTOR() - leaves result in ACC at runtime
<factor> ::= (+|-) identifier | number
"""
#Numbers
if token.token == idsym:
emit(0, "load", token.address)
getoken()
elif token.token == number:
emit(0, "loadv", token.value)
getoken()
elif token.token == semicolon: getoken()
else: error("Start of Factor expected")
#===============================================================================
def program():
#===============================================================================
""" # PROGRAM - Start production of the grammar
# <program> ::= { <id> ; <vars > <stmtlist> }
"""
if token.token == leftbrace: getoken()
else: error(" { expected")
if token.token == idsym: getoken()
else: error("Program name expected")
if token.token == semicolon: getoken()
else: error("Semicolon expected")
if token.token == varsym : vars()
stmtList()
if token.token == halt:
print("\n#*** Stop execution ***\n")
elif token.token == rightbrace:
print("\n#*** Compilation finished ***\n")
else: error(" } expected")
# Compiler main function
#======================================================================
def main():
#======================================================================
global line
global srcfile
global outfile
global charIndex
initSymTbl()
# srcfile = open('while_If_forever_loop.txt', 'r')
# srcfile = open('while_If_Continue_restart_loop.txt', 'r')
srcfile = open('Read_Write_int_ch.txt', 'r')
line = srcfile.read() # readline
# for line in open('tiny.txt', 'r'):
# if not line.startswith("#"):
# debugScanner = False
charIndex = 0
debugScanner = False
if debugScanner: # Scanner Test Routine - Read a line and display the tokens
getoken()
while token.token is not None: # Skeleton for testing Scanner
printToken(token)
# outfile.write(token)
getoken()
sys.exit(1)
else:
getoken() # Parse Program according to the grammar
program() # Call start non-terminal handler
#===============================================================================
# Main Compiler starts here
#===============================================================================
print "#Microcompiler.py v0.2"
emit(0, "load", 0)
emit(0, "constant", "'A'")
emit(0, "constant", 10)
emit(0, "constant", 12)
emit(0, "constant", 25)
emit(0, "constant", -10)
main()
#srcfile = open('tiny.txt', 'r')
#lexer = shlex.shlex(srcfile)
#for token in lexer:
# print repr(token)
#getoken()
| [
[
8,
0,
0.0139,
0.0196,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0261,
0.0016,
0,
0.66,
0.0213,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.0278,
0.0016,
0,
0.66... | [
"\"\"\" Giovanni's MicroCompiler Demo\n\n<program> ::= { <id> ; <vars > <stmtlist> }\n<vars> ::= V { <id> ; } % DECLARATIONS\n\n<stmtlist> ::= <stmt> { ; <stmt> }\n<stmt> ::= P <id> | <id> = <expr>",
"import sys",
"import shlex",
"tokenName... |
""" Giovanni's MicroCompiler Demo
<program> ::= { <id> ; <vars > <stmtlist> }
<vars> ::= V { <id> ; } % DECLARATIONS
<stmtlist> ::= <stmt> { ; <stmt> }
<stmt> ::= P <id> | <id> = <expr>
<expr> ::= <factor> { (+ | -) <factor> } % No precedence
<factor> ::= (+|-) ID | Number
"""
import sys
import shlex
#===============================================================================
# # Lexical Analyser - the "Scanner" - Define the TokenTypes
#===============================================================================
tokenNames =\
[ "unknownToken", "idsym", "assignsym", "leftbrace", "rightbrace",
"varsym", "semicolon", "whilesym", "leftbracket", "rightbracket",
"printsym", "ifsym", "elsesym", "equals", "notequals", "lessthan", "greaterthan",
"readch", "readint", "writech", "writeint",
"number", "plus", "minus", "mpy", "div", "jumpne", "jumpeq","lessthanequal","greaterthanequal", "endfile"]
# define the tokens as variables
unknownToken, idsym, assignsym, leftbrace, rightbrace,\
varsym, semicolon, whilesym, leftbracket, rightbracket,\
printsym, ifsym, elsesym, equals, notequals, lessthan, greaterthan,\
readch, readint, writech, writeint,\
number, plus, minus, mpy, div, jumpne, jumpeq, lessthanequal, greaterthanequal, endfile = range(0, len(tokenNames))
#===============================================================================
class symbol:
#===============================================================================
name = None # String representation
token = None; # Corresponding token
address = 0; # For variables, their runtime address
value = None # on defined for numbers
def __init__(self, name, token, value = 0):
self.name = name
self.token = token
self.address = 0 # for identifiers, their address
self.value = value # for numbers, their value
symtbl = {}; # The Symbol Table, a dictionary of symbols indexed by name
#======================================================================
# GLOBALS for output of Lexical Analyser
# Set by each call to GeToken()
token = None; # A symbol
line = "\n" # the complex source file as a string
charIndex = 0 # the position in the source
linenumber= 0 # The current number
EOF = chr(0)
#======================================================================
# Run Time Code Generation Variables
varptr = 500 # Arbitrary base address of memory for variables
codeptr = 10 # Address to output next instruction (for code)
#===============================================================================
# Symbol Table Management Routines
#===============================================================================
#===============================================================================
def addToSymTbl (name, token):
#===============================================================================
symtbl[name] = symbol(name, token) # Add a new symbol to the dictionary
return symtbl[name]
#===============================================================================
def lookup (thisName):
#===============================================================================
"# Find a given identifier in the Symbol Table, Return the symtbl entry"
if symtbl.has_key(thisName): # thisName has been seen before
return symtbl[thisName] # return the symtbl entry
else: return None
#===============================================================================
def initSymTbl():
#===============================================================================
"# Initialise Symbol Table, and preload reserved words"
addToSymTbl('var', varsym) # VAR
addToSymTbl('while', whilesym) # WHILE
addToSymTbl('for', whilesym) # WHILE
addToSymTbl('print', printsym) # PRINT
addToSymTbl('if', ifsym) # IF
addToSymTbl('else', elsesym) # ELSE
addToSymTbl('readint', readint) #READINT
addToSymTbl('writeint', writeint) #READINT
addToSymTbl('readch', readch) #READINT
addToSymTbl('writech', writech) #READINT
# Now add symbols - NB only single character symbols are here
# multicharacter one like ">=" are still to do
addToSymTbl( '=', assignsym)
addToSymTbl( '#', notequals)
addToSymTbl( '<', lessthan) #jumplt
addToSymTbl( '>', greaterthan) #jumpgt
addToSymTbl( '{', leftbrace )
addToSymTbl( '}', rightbrace)
addToSymTbl( '(', leftbracket)
addToSymTbl( ')', rightbracket)
addToSymTbl( '+', plus )
addToSymTbl( '-', minus)
addToSymTbl( '*', mpy)
addToSymTbl( '/', div)
addToSymTbl( ';', semicolon)
addToSymTbl( EOF, endfile)
#multicharacter one like ">=" are still to do
addToSymTbl( '==', jumpeq)
addToSymTbl( '!=', jumpne)
addToSymTbl( '<=', lessthanequal) #jumplt
addToSymTbl( '>=', greaterthanequal) #jumpgt
#===============================================================================
# Scanner Diagnostics
#===============================================================================
def printToken(tok):
#===============================================================================
" - display the specified token."
if tok.token == idsym:
print "Token = %10s, %-10s adr = %3d" %\
(tokenNames[tok.token], tok.name, tok.address)
elif tok.token == number:
print "Token = %10s %d" % (tokenNames[tok.token], tok.value)
else:
print "Token = %10s" % tokenNames[tok.token]
#==============================?=================================================
def dumpSymTbl():
#===============================================================================
""" Dump all the tokens in the symboltable """
print(" *** Symbol Table ***")
for name in symtbl.keys(): # keys is a list of the names (printable form of tokens)
tok = symtbl[name]
if tok.token == idsym:
printToken(tok)
#===============================================================================
def getch():
#===============================================================================
global line
global charIndex
global linenumber
while True:
if charIndex < len(line): # See if used up current line
ch = line[charIndex] # if not, get character
charIndex = charIndex+1 # & move pointer for next time
else:
#line = srcfile.readline()
if line == "": line = EOF
print "--> ",
line = raw_input() +"\n" # read new line, adding \n so it's like f.readline()
charIndex = 0 # & reset character pointer
linenumber = linenumber + 1
continue
if ch == "\n":
ch = " " # A newline is a token separator
if ch == "?":
dumpSymTbl()
continue
return ch
#===============================================================================
def ungetch():
#===============================================================================
""" Unget the next character peeked at when building variables, numbers
and when distinguishing between >= and > ...
"""
global charIndex;
charIndex = charIndex-1;
#===============================================================================
def getoken():
#===============================================================================
""" GETOKEN - Put next token into the global TOKEN """
global token
ch = getch() # skip whitespace
while ch in ["\t", " ", "\n", "#"]:
ch = getch()
# If ch is alphabetic then this is start of reserved word or an identifier
if ch.isalpha(): # Letter therefore it's either identifier or reserved word
name = ""
while ch.isalpha() or ch.isdigit() or ch == "_":
name = name + ch
ch = getch()
ungetch() # let terminator be used next time
token = lookup(name) # See if token's known
if token is None: # if not
token = addToSymTbl(name, idsym) # add as 'idsym'-IDENTIFIER
return # we've set token.token to either id or tokentype of reserved word
#---------------------------------------------------------------------
# If it's numeric return TOKEN=number & token.value = binary value
elif ch.isdigit():
# In the real version, build number and don't forget to end with ungetch()
token = symbol(ch, number, value = int(ch)) # simplistic SINGLE DIGIT Ascii to Binary
return
#---------------------------------------------------------------------
# Single character tokens
elif ch in ["=", "#", "<", ">", "{", "}", "(", ")", "+" , "-", "*", "/", ";","!", "==", EOF]:
token = lookup(ch) # preloaded with appropriate token
else:
print "Unknown character -->%s<- decimal %d" % (ch,ord(ch))
sys.exit(1) # Abort Compilation
#======================================================================
# THE GRAMMAR
# <program> ::= { <id> ; <vars > <stmtlist> }
# <vars> ::= var { <id> ; } % DECLARATIONS
# <array> ::= [<expr>]
# <stmtlist> ::= <stmt> { ; <stmt> }
# <stmt> ::= print <id>
# <id> = <expr>
# <expr> ::= <factor> { (+ | -) <factor> } % No precedence
# <factor> ::= [+/-] ID | Number
#======================================================================
# Centralised Parser Error Message handler
#======================================================================
#===============================================================================
def error (msg):
#===============================================================================
print line
print "-" * charIndex,"^"
print("Error on %d - %s\n" % (number, msg))
printToken(token)
print("\n")
#===============================================================================
def emit (memadr, opcode, parameter):
#===============================================================================
"""EMIT CODE - Emit a of code with a Parameter
if first arg is zero - (the memory address), use and incr CODEPTR"""
global codeptr
if (memadr == 0):
memadr = codeptr
codeptr = codeptr+1
print "%6d %-8s %-7s" % (memadr, opcode, parameter)
#======================================================================
# VARIABLE DECLARATIONS
# <vars> ::= V { <id> ; }
#===============================================================================
def vars() :
#===============================================================================
global varptr;
getoken(); #skip VARSYM - already been recognised
while (token.token == idsym):
if token.address != 0:
print("%c already declared\n", token.name);
else:
symtbl[token.name].address = varptr;
varptr = varptr +1
getoken(); #skip past identifier
if token.token == semicolon: getoken() #skip ;
else: error("semicolon expected in declaration")
#======================================================================
# STMTLIST
# <stmtlist> ::= <stmt> { ; <stmt> }
#===============================================================================
def stmtList():
#===============================================================================
stmt()
while (token.token == semicolon):
getoken() #skip ;
stmt()
#======================================================================
# STMT
#===============================================================================
def stmt():
#===============================================================================
""" <stmt> ::= print <expression> | <id> = <expression> | if <expression> | while <expression>
"""
global codeptr
thisStmtAdr = codeptr # Jump DEMO - not part of Stmt
if token.token == printsym:
printStmt()
elif token.token == idsym:
assignStmt()
elif token.token == ifsym:
ifStmt()
elif token.token == elsesym:
elseStmt()
elif token.token == whilesym:
whileStmt()
elif token.token == readint:
readIntStmt()
elif token.token == readch:
readChStmt()
elif token.token == writeint:
writeIntStmt()
elif token.token == writech:
writeChStmt()
else:
error("Expected start of a statement")
# emit (0, "return", thisStmtAdr) # Jump DEMO
#===============================================================================
def printStmt():
#===============================================================================
""" <printStmt> ::= print <expression>"""
getoken() # skip "print"
expression() # on return, expr result (at runtime) will be in ACC
emit(0, "writeint", 0) # Memory address 0 is the ACC
if token.token == rightbrace:
print("\n*** Compilation finished ***\n")
#===============================================================================
def assignStmt():
#===============================================================================
"""
<id> = <expression>
"""
whichidentifier = token # Remember which ID on Left
getoken() # Get token after identifier
if token.token == notequals:
srcfile.read()
# getoken()
elif token.token == assignsym:
getoken()
elif token.token == jumpeq:
getoken()
elif token.token == semicolon:getoken()
else:
error("Expected = in assignment statement")
expression()
# Save result into LHS runtime address
#===============================================================================
def ifStmt():
#if-then-else
#===============================================================================
""" <ifStmt> ::= if <expression>"""
getoken() # skip "if"
if token.token == lessthan:
print("lessthan")
getoken()
expression()
stmt()
if token.token == semicolon:getoken()
#===============================================================================
def elseStmt():
#if-then-else
#===============================================================================
""" <elseStmt> ::= else <expression>"""
getoken()
emit(0, "store", 888)
stmt()
#===============================================================================
def whileStmt():
#===============================================================================
""" <whileStmt> ::= while (condition)statement"""
getoken() # skip "if"
emit(0, "compare",50)
expression()
stmt()
emit(0, "increment", 1)
emit(0, "jumpi", 14)
#===============================================================================
def readIntStmt():
#===============================================================================
getoken()
expression() # skip "if"
emit(0, "readint",999)
#===============================================================================
def readChStmt():
#===============================================================================
getoken() # skip "if"
emit(0, "readch",11)
#===============================================================================
def writeIntStmt():
#===============================================================================
getoken() # skip "if"
expression()
emit(0, "writeint",50)
#===============================================================================
def writeChStmt():
#===============================================================================
getoken() # skip "if"
emit(0, "writech",51)
#===============================================================================
def expression():
#===============================================================================
"""
Leaves result in ACC at runtime
Use addresses 999 & 998 as Temporary variables
<expression> ::= <factor> { (+ | - | * | /) <factor> }
"""
factor()
while token.token == plus or token.token == minus or token.token == mpy or token.token == div or token.token == lessthan or token.token == greaterthan or token.token == jumpne or token.token == jumpeq:
op = token # remember +/-
getoken() # skip past +/-
emit(0, "store", 999) # Save current result
factor() # Evaluate next factor
#working
if op.token == plus:
emit(0, "add", 999)
emit(0, "store", 999)
if op.token == leftbracket:getoken()
elif op.token == minus: # Subtract - have to swap operand order
emit(0, "subtract", 998) # Leaves result in Acc
emit(0, "store", 6)
elif op.token == mpy:
emit(0, "mpy", 998)
emit(0, "store", 7)
elif op.token == div:
emit(0, "div", 998)
emit(0, "store", 8)
elif op.token == lessthan:
emit(0, "compare",105 )
emit(0, "jumplt", 150)
emit(150, "halt", 0)
#===============================================================================
def factor():
#===============================================================================
"""
# FACTOR() - leaves result in ACC at runtime
<factor> ::= (+|-) identifier | number
"""
#Numbers
if token.token == idsym:
emit(0, "load", token.address)
getoken()
elif token.token == number:
emit(0, "loadv", token.value)
emit(0, "store", token.value+100)
getoken()
elif token.token == rightbrace:print("")
else: error("Start of Factor expected")
#===============================================================================
def program():
#===============================================================================
""" # PROGRAM - Start production of the grammar
# <program> ::= { <id> ; <vars > <stmtlist> }
"""
if token.token == leftbrace: getoken()
else: error(" { expected")
if token.token == idsym: getoken()
else: error("Program name expected")
if token.token == semicolon: getoken()
else: error("Semicolon expected")
if token.token == varsym : vars()
stmtList()
if token.token == rightbrace:
print("\n*** Compilation finished ***\n")
else: error(" } expected")
# Compiler main function
#======================================================================
def main():
#======================================================================
global line
global srcfile
global outfile
global charIndex
initSymTbl()
srcfile = open('break.txt', 'r')
line = srcfile.read() # readline
# for line in open('tiny.txt', 'r'):
# if not line.startswith("#"):
# debugScanner = False
charIndex = 0
debugScanner = False
if debugScanner: # Scanner Test Routine - Read a line and display the tokens
getoken()
while token.token is not None: # Skeleton for testing Scanner
printToken(token)
# outfile.write(token)
getoken()
srcfile.close()
sys.exit(1)
else:
getoken() # Parse Program according to the grammar
program() # Call start non-terminal handler
#===============================================================================
# Main Compiler starts here
#===============================================================================
print "#Microcompiler.py v0.2"
emit(0, "load", 0)
#emit(0, "constant", "'A'")
#emit(0, "constant", 10)
#emit(0, "constant", 12)
#emit(0, "constant", 25)
#emit(0, "constant", -10)
main()
#srcfile = open('tiny.txt', 'r')
#lexer = shlex.shlex(srcfile)
#for token in lexer:
# print repr(token)
#getoken()
| [
[
8,
0,
0.0147,
0.0208,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0277,
0.0017,
0,
0.66,
0.0238,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.0294,
0.0017,
0,
0.66... | [
"\"\"\" Giovanni's MicroCompiler Demo\n\n<program> ::= { <id> ; <vars > <stmtlist> }\n<vars> ::= V { <id> ; } % DECLARATIONS\n\n<stmtlist> ::= <stmt> { ; <stmt> }\n<stmt> ::= P <id> | <id> = <expr>",
"import sys",
"import shlex",
"tokenName... |
""" Giovanni's MicroCompiler Demo
<program> ::= { <id> ; <vars > <stmtlist> }
<vars> ::= V { <id> ; } % DECLARATIONS
<stmtlist> ::= <stmt> { ; <stmt> }
<stmt> ::= P <id> | <id> = <expr>
<expr> ::= <factor> { (+ | -) <factor> } % No precedence
<factor> ::= (+|-) ID | Number
"""
import sys
import shlex
#===============================================================================
# # Lexical Analyser - the "Scanner" - Define the TokenTypes
#===============================================================================
tokenNames =\
[ "unknownToken", "idsym", "assignsym", "leftbrace", "rightbrace",
"varsym", "semicolon", "whilesym", "leftbracket", "rightbracket",
"printsym", "ifsym", "elsesym", "equals", "notequals", "lessthan", "greaterthan",
"readch", "readint", "writech", "writeint",
"number", "plus", "minus", "mpy", "div", "jumpne", "jumpeq","lessthanequal","greaterthanequal", "endfile"]
# define the tokens as variables
unknownToken, idsym, assignsym, leftbrace, rightbrace,\
varsym, semicolon, whilesym, leftbracket, rightbracket,\
printsym, ifsym, elsesym, equals, notequals, lessthan, greaterthan,\
readch, readint, writech, writeint,\
number, plus, minus, mpy, div, jumpne, jumpeq, lessthanequal, greaterthanequal, endfile = range(0, len(tokenNames))
#===============================================================================
class symbol:
#===============================================================================
name = None # String representation
token = None; # Corresponding token
address = 0; # For variables, their runtime address
value = None # on defined for numbers
def __init__(self, name, token, value = 0):
self.name = name
self.token = token
self.address = 0 # for identifiers, their address
self.value = value # for numbers, their value
symtbl = {}; # The Symbol Table, a dictionary of symbols indexed by name
#======================================================================
# GLOBALS for output of Lexical Analyser
# Set by each call to GeToken()
token = None; # A symbol
line = "\n" # the complex source file as a string
charIndex = 0 # the position in the source
linenumber= 0 # The current number
EOF = chr(0)
#======================================================================
# Run Time Code Generation Variables
varptr = 500 # Arbitrary base address of memory for variables
codeptr = 10 # Address to output next instruction (for code)
#===============================================================================
# Symbol Table Management Routines
#===============================================================================
#===============================================================================
def addToSymTbl (name, token):
#===============================================================================
symtbl[name] = symbol(name, token) # Add a new symbol to the dictionary
return symtbl[name]
#===============================================================================
def lookup (thisName):
#===============================================================================
"# Find a given identifier in the Symbol Table, Return the symtbl entry"
if symtbl.has_key(thisName): # thisName has been seen before
return symtbl[thisName] # return the symtbl entry
else: return None
#===============================================================================
def initSymTbl():
#===============================================================================
"# Initialise Symbol Table, and preload reserved words"
addToSymTbl('var', varsym) # VAR
addToSymTbl('while', whilesym) # WHILE
addToSymTbl('for', whilesym) # WHILE
addToSymTbl('print', printsym) # PRINT
addToSymTbl('if', ifsym) # IF
addToSymTbl('else', elsesym) # ELSE
addToSymTbl('readint', readint) #READINT
addToSymTbl('writeint', writeint) #READINT
addToSymTbl('readch', readch) #READINT
addToSymTbl('writech', writech) #READINT
# Now add symbols - NB only single character symbols are here
# multicharacter one like ">=" are still to do
addToSymTbl( '=', assignsym)
addToSymTbl( '#', notequals)
addToSymTbl( '<', lessthan) #jumplt
addToSymTbl( '>', greaterthan) #jumpgt
addToSymTbl( '{', leftbrace )
addToSymTbl( '}', rightbrace)
addToSymTbl( '(', leftbracket)
addToSymTbl( ')', rightbracket)
addToSymTbl( '+', plus )
addToSymTbl( '-', minus)
addToSymTbl( '*', mpy)
addToSymTbl( '/', div)
addToSymTbl( ';', semicolon)
addToSymTbl( EOF, endfile)
#multicharacter one like ">=" are still to do
addToSymTbl( '==', jumpeq)
addToSymTbl( '!=', jumpne)
addToSymTbl( '<=', lessthanequal) #jumplt
addToSymTbl( '>=', greaterthanequal) #jumpgt
#===============================================================================
# Scanner Diagnostics
#===============================================================================
def printToken(tok):
#===============================================================================
" - display the specified token."
if tok.token == idsym:
print "Token = %10s, %-10s adr = %3d" %\
(tokenNames[tok.token], tok.name, tok.address)
elif tok.token == number:
print "Token = %10s %d" % (tokenNames[tok.token], tok.value)
else:
print "Token = %10s" % tokenNames[tok.token]
#==============================?=================================================
def dumpSymTbl():
#===============================================================================
""" Dump all the tokens in the symboltable """
print(" *** Symbol Table ***")
for name in symtbl.keys(): # keys is a list of the names (printable form of tokens)
tok = symtbl[name]
if tok.token == idsym:
printToken(tok)
#===============================================================================
def getch():
#===============================================================================
global line
global charIndex
global linenumber
while True:
if charIndex < len(line): # See if used up current line
ch = line[charIndex] # if not, get character
charIndex = charIndex+1 # & move pointer for next time
else:
#line = srcfile.readline()
#if line == "": line = EOF
#if line == "#": line = notequals
print "--> ",
line = raw_input() +"\n" # read new line, adding \n so it's like f.readline()
charIndex = 0 # & reset character pointer
linenumber = linenumber + 1
continue
if ch == "\n":
ch = " " # A newline is a token separator
if ch == "?":
dumpSymTbl()
continue
return ch
#===============================================================================
def ungetch():
#===============================================================================
""" Unget the next character peeked at when building variables, numbers
and when distinguishing between >= and > ...
"""
global charIndex;
charIndex = charIndex-1;
#===============================================================================
def getoken():
#===============================================================================
""" GETOKEN - Put next token into the global TOKEN """
global token
ch = getch() # skip whitespace
while ch in ["\t", " ", "\n", "#"]:
ch = getch()
# If ch is alphabetic then this is start of reserved word or an identifier
if ch.isalpha(): # Letter therefore it's either identifier or reserved word
name = ""
while ch.isalpha() or ch.isdigit() or ch == "_":
name = name + ch
ch = getch()
ungetch() # let terminator be used next time
token = lookup(name) # See if token's known
if token is None: # if not
token = addToSymTbl(name, idsym) # add as 'idsym'-IDENTIFIER
return # we've set token.token to either id or tokentype of reserved word
#---------------------------------------------------------------------
# If it's numeric return TOKEN=number & token.value = binary value
elif ch.isdigit():
# In the real version, build number and don't forget to end with ungetch()
token = symbol(ch, number, value = int(ch)) # simplistic SINGLE DIGIT Ascii to Binary
return
#---------------------------------------------------------------------
# Single character tokens
elif ch in ["=", "#", "<", ">", "{", "}", "(", ")", "+" , "-", "*", "/", ";","!", "==", EOF]:
token = lookup(ch) # preloaded with appropriate token
else:
print "Unknown character -->%s<- decimal %d" % (ch,ord(ch))
sys.exit(1) # Abort Compilation
#======================================================================
# THE GRAMMAR
# <program> ::= { <id> ; <vars > <stmtlist> }
# <vars> ::= var { <id> ; } % DECLARATIONS
# <stmtlist> ::= <stmt> { ; <stmt> }
# <stmt> ::= print <id>
# <id> = <expr>
# <expr> ::= <factor> { (+ | -) <factor> } % No precedence
# <factor> ::= ID | Number
#======================================================================
# Centralised Parser Error Message handler
#======================================================================
#===============================================================================
def error (msg):
#===============================================================================
print line
print "-" * charIndex,"^"
print("Error on %d - %s\n" % (number, msg))
printToken(token)
print("\n")
#===============================================================================
def emit (memadr, opcode, parameter):
#===============================================================================
"""EMIT CODE - Emit a of code with a Parameter
if first arg is zero - (the memory address), use and incr CODEPTR"""
global codeptr
if (memadr == 0):
memadr = codeptr
codeptr = codeptr+1
print "%6d %-8s %-7s" % (memadr, opcode, parameter)
#======================================================================
# VARIABLE DECLARATIONS
# <vars> ::= V { <id> ; }
#===============================================================================
def vars() :
#===============================================================================
global varptr;
getoken(); #skip VARSYM - already been recognised
while (token.token == idsym):
if token.address != 0:
print("%c already declared\n", token.name);
else:
symtbl[token.name].address = varptr;
varptr = varptr +1
getoken(); #skip past identifier
if token.token == semicolon: getoken() #skip ;
else: error("semicolon expected in declaration")
#======================================================================
# STMTLIST
# <stmtlist> ::= <stmt> { ; <stmt> }
#===============================================================================
def stmtList():
#===============================================================================
stmt()
while (token.token == semicolon):
getoken() #skip ;
stmt()
#======================================================================
# STMT
#===============================================================================
def stmt():
#===============================================================================
""" <stmt> ::= print <expression> | <id> = <expression> | if <expression> | while <expression>
"""
global codeptr
# thisStmtAdr = codeptr # Jump DEMO - not part of Stmt
if token.token == printsym:
printStmt()
elif token.token == idsym:
assignStmt()
elif token.token == ifsym:
ifStmt()
elif token.token == elsesym:
elseStmt()
elif token.token == whilesym:
whileStmt()
elif token.token == readint:
readIntStmt()
elif token.token == readch:
readChStmt()
elif token.token == writeint:
writeIntStmt()
elif token.token == writech:
writeChStmt()
elif token.token == rightbrace:
print("\n#*** Compilation finished ***\n")
else:
error("Expected start of a statement")
# emit (0, "return", thisStmtAdr) # Jump DEMO
#===============================================================================
def printStmt():
#===============================================================================
""" <printStmt> ::= print <expression>"""
getoken() # skip "print"
expression() # on return, expr result (at runtime) will be in ACC
emit(0, "writeint", 0) # Memory address 0 is the ACC
if token.token == rightbrace:
print("\n#*** Compilation finished ***\n")
#===============================================================================
def assignStmt():
#===============================================================================
"""
<id> = <expression>
"""
whichidentifier = token # Remember which ID on Left
getoken() # Get token after identifier
if token.token == assignsym:
getoken()
elif token.token == jumpeq:
getoken()
else:
error("Expected = in assignment statement")
expression()
# Save result into LHS runtime address
#===============================================================================
def ifStmt():
#if-then-else
#===============================================================================
""" <ifStmt> ::= if <expression>"""
getoken() # skip "if"
emit(0, "compare",60)
expression()
stmt()
emit(0, "return",0)
#===============================================================================
def elseStmt():
#if-then-else
#===============================================================================
""" <elseStmt> ::= else <expression>"""
getoken()
emit(0, "store", 888)
stmt()
#===============================================================================
def whileStmt():
#===============================================================================
""" <whileStmt> ::= while (condition)statement"""
getoken() # skip "if"
emit(0, "compare",50)
expression()
stmt()
emit(0, "increment", 1)
emit(0, "jumpi", 14)
#===============================================================================
def readIntStmt():
#===============================================================================
getoken()
expression() # skip "if"
emit(0, "readint",999)
#===============================================================================
def readChStmt():
#===============================================================================
getoken() # skip "if"
emit(0, "readch",11)
#===============================================================================
def writeIntStmt():
#===============================================================================
getoken() # skip "if"
expression()
emit(0, "writeint",50)
#===============================================================================
def writeChStmt():
#===============================================================================
getoken() # skip "if"
emit(0, "writech",51)
#===============================================================================
def expression():
#===============================================================================
"""
Leaves result in ACC at runtime
Use addresses 999 & 998 as Temporary variables
<expression> ::= <factor> { (+ | - | * | /) <factor> }
"""
factor()
while token.token == plus or token.token == minus or token.token == mpy or token.token == div or token.token == lessthan or token.token == greaterthan or token.token == jumpne or token.token == jumpeq:
op = token # remember +/-
getoken() # skip past +/-
emit(0, "store", 999) # Save current result
factor() # Evaluate next factor
#working
if op.token == plus:
emit(0, "loadv", 999)
emit(0, "add", 999)
emit(0, "store", 999)
if op.token == leftbracket:getoken()
elif op.token == minus: # Subtract - have to swap operand order
emit(0, "store", 998)
emit(0, "load" , 999)
emit(0, "subtract", 998) # Leaves result in Acc
emit(0, "store", 6)
elif op.token == mpy:
emit(0, "store", 998)
emit(0, "load", 999)
emit(0, "mpy", 998)
emit(0, "store", 7)
elif op.token == div:
emit(0, "store", 998)
emit(0, "load", 999)
emit(0, "div", 998)
emit(0, "store", 8)
elif op.token == lessthan:
emit(0, "store", 998)
emit(0, "compare", 999)
emit(0, "jumplt", 80)
emit(0, "loadv", 0)
emit(0, "store", 9)
elif op.token == greaterthan:
emit(0, "store", 998)
emit(0, "compare", 999)
emit(0, "jumpgt", 81)
emit(0, "loadv", 0)
emit(0, "store", 10)
#not working
elif op.token == jumpne:
emit(0, "store", 998)
emit(0, "compare", 999)
emit(0, "jumpne", 82)
emit(0, "loadv", 0)
emit(0, "store", 11)
elif op.token == jumpeq:
emit(0, "store", 998)
emit(0, "compare", 999)
emit(0, "jumpeq", 83)
#===============================================================================
def factor():
#===============================================================================
"""
# FACTOR() - leaves result in ACC at runtime
<factor> ::= (+|-) identifier | number
"""
#Numbers
if token.token == idsym:
emit(0, "load", token.address)
getoken()
elif token.token == number:
emit(0, "loadv", token.value)
getoken()
else: error("Start of Factor expected")
#===============================================================================
def program():
#===============================================================================
""" # PROGRAM - Start production of the grammar
# <program> ::= { <id> ; <vars > <stmtlist> }
"""
if token.token == leftbrace: getoken()
else: error(" { expected")
if token.token == idsym: getoken()
else: error("Program name expected")
if token.token == semicolon: getoken()
else: error("Semicolon expected")
if token.token == varsym : vars()
stmtList()
if token.token == rightbrace:
print("\n#*** Compilation finished ***\n")
else: error(" } expected")
# Compiler main function
#======================================================================
def main():
#======================================================================
global line
global srcfile
global outfile
global charIndex
initSymTbl()
# srcfile = open('while_If_forever_loop.txt', 'r')
# srcfile = open('while_If_Continue_restart_loop.txt', 'r')
srcfile = open('Read_Write_int_ch.txt', 'r')
line = srcfile.read() # readline
# for line in open('tiny.txt', 'r'):
# if not line.startswith("#"):
# debugScanner = False
charIndex = 0
debugScanner = False
if debugScanner: # Scanner Test Routine - Read a line and display the tokens
getoken()
while token.token is not None: # Skeleton for testing Scanner
printToken(token)
# outfile.write(token)
getoken()
sys.exit(1)
else:
getoken() # Parse Program according to the grammar
program() # Call start non-terminal handler
#===============================================================================
# Main Compiler starts here
#===============================================================================
print "#Microcompiler.py v0.2"
emit(0, "load", 0)
emit(0, "constant", "'A'")
emit(0, "constant", 10)
emit(0, "constant", 12)
emit(0, "constant", 25)
emit(0, "constant", -10)
main()
#srcfile = open('tiny.txt', 'r')
#lexer = shlex.shlex(srcfile)
#for token in lexer:
# print repr(token)
#getoken()
| [
[
8,
0,
0.014,
0.0198,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0264,
0.0017,
0,
0.66,
0.0213,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.0281,
0.0017,
0,
0.66,... | [
"\"\"\" Giovanni's MicroCompiler Demo\n\n<program> ::= { <id> ; <vars > <stmtlist> }\n<vars> ::= V { <id> ; } % DECLARATIONS\n\n<stmtlist> ::= <stmt> { ; <stmt> }\n<stmt> ::= P <id> | <id> = <expr>",
"import sys",
"import shlex",
"tokenName... |
""" Giovanni's MicroCompiler Demo
<program> ::= { <id> ; <vars > <stmtlist> }
<vars> ::= V { <id> ; } % DECLARATIONS
<stmtlist> ::= <stmt> { ; <stmt> }
<stmt> ::= P <id> | <id> = <expr>
<expr> ::= <factor> { (+ | -) <factor> } % No precedence
<factor> ::= (+|-) ID | Number
"""
import sys
import shlex
#===============================================================================
# # Lexical Analyser - the "Scanner" - Define the TokenTypes
#===============================================================================
tokenNames =\
[ "unknownToken", "idsym", "assignsym", "leftbrace", "rightbrace",
"varsym", "semicolon", "whilesym", "leftbracket", "rightbracket",
"printsym", "ifsym", "elsesym", "equals", "notequals", "lessthan", "greaterthan",
"readch", "readint", "writech", "writeint",
"number", "plus", "minus", "mpy", "div", "jumpne", "jumpeq","lessthanequal","greaterthanequal", "endfile"]
# define the tokens as variables
unknownToken, idsym, assignsym, leftbrace, rightbrace,\
varsym, semicolon, whilesym, leftbracket, rightbracket,\
printsym, ifsym, elsesym, equals, notequals, lessthan, greaterthan,\
readch, readint, writech, writeint,\
number, plus, minus, mpy, div, jumpne, jumpeq, lessthanequal, greaterthanequal, endfile = range(0, len(tokenNames))
#===============================================================================
class symbol:
#===============================================================================
name = None # String representation
token = None; # Corresponding token
address = 0; # For variables, their runtime address
value = None # on defined for numbers
def __init__(self, name, token, value = 0):
self.name = name
self.token = token
self.address = 0 # for identifiers, their address
self.value = value # for numbers, their value
symtbl = {}; # The Symbol Table, a dictionary of symbols indexed by name
#======================================================================
# GLOBALS for output of Lexical Analyser
# Set by each call to GeToken()
token = None; # A symbol
line = "\n" # the complex source file as a string
charIndex = 0 # the position in the source
linenumber= 0 # The current number
EOF = chr(0)
#======================================================================
# Run Time Code Generation Variables
varptr = 500 # Arbitrary base address of memory for variables
codeptr = 10 # Address to output next instruction (for code)
#===============================================================================
# Symbol Table Management Routines
#===============================================================================
#===============================================================================
def addToSymTbl (name, token):
#===============================================================================
symtbl[name] = symbol(name, token) # Add a new symbol to the dictionary
return symtbl[name]
#===============================================================================
def lookup (thisName):
#===============================================================================
"# Find a given identifier in the Symbol Table, Return the symtbl entry"
if symtbl.has_key(thisName): # thisName has been seen before
return symtbl[thisName] # return the symtbl entry
else: return None
#===============================================================================
def initSymTbl():
#===============================================================================
"# Initialise Symbol Table, and preload reserved words"
addToSymTbl('var', varsym) # VAR
addToSymTbl('while', whilesym) # WHILE
addToSymTbl('for', whilesym) # WHILE
addToSymTbl('print', printsym) # PRINT
addToSymTbl('if', ifsym) # IF
addToSymTbl('else', elsesym) # ELSE
addToSymTbl('readint', readint) #READINT
addToSymTbl('writeint', writeint) #READINT
addToSymTbl('readch', readch) #READINT
addToSymTbl('writech', writech) #READINT
# Now add symbols - NB only single character symbols are here
# multicharacter one like ">=" are still to do
addToSymTbl( '=', assignsym)
addToSymTbl( '#', notequals)
addToSymTbl( '<', lessthan) #jumplt
addToSymTbl( '>', greaterthan) #jumpgt
addToSymTbl( '{', leftbrace )
addToSymTbl( '}', rightbrace)
addToSymTbl( '(', leftbracket)
addToSymTbl( ')', rightbracket)
addToSymTbl( '+', plus )
addToSymTbl( '-', minus)
addToSymTbl( '*', mpy)
addToSymTbl( '/', div)
addToSymTbl( ';', semicolon)
addToSymTbl( EOF, endfile)
#multicharacter one like ">=" are still to do
addToSymTbl( '==', jumpeq)
addToSymTbl( '!=', jumpne)
addToSymTbl( '<=', lessthanequal) #jumplt
addToSymTbl( '>=', greaterthanequal) #jumpgt
#===============================================================================
# Scanner Diagnostics
#===============================================================================
def printToken(tok):
#===============================================================================
" - display the specified token."
if tok.token == idsym:
print "Token = %10s, %-10s adr = %3d" %\
(tokenNames[tok.token], tok.name, tok.address)
elif tok.token == number:
print "Token = %10s %d" % (tokenNames[tok.token], tok.value)
else:
print "Token = %10s" % tokenNames[tok.token]
#==============================?=================================================
def dumpSymTbl():
#===============================================================================
""" Dump all the tokens in the symboltable """
print(" *** Symbol Table ***")
for name in symtbl.keys(): # keys is a list of the names (printable form of tokens)
tok = symtbl[name]
if tok.token == idsym:
printToken(tok)
#===============================================================================
def getch():
#===============================================================================
global line
global charIndex
global linenumber
while True:
if charIndex < len(line): # See if used up current line
ch = line[charIndex] # if not, get character
charIndex = charIndex+1 # & move pointer for next time
else:
#line = srcfile.readline()
#if line == "": line = EOF
#if line == "#": line = notequals
print "--> ",
line = raw_input() +"\n" # read new line, adding \n so it's like f.readline()
charIndex = 0 # & reset character pointer
linenumber = linenumber + 1
continue
if ch == "\n":
ch = " " # A newline is a token separator
if ch == "?":
dumpSymTbl()
continue
return ch
#===============================================================================
def ungetch():
#===============================================================================
""" Unget the next character peeked at when building variables, numbers
and when distinguishing between >= and > ...
"""
global charIndex;
charIndex = charIndex-1;
#===============================================================================
def getoken():
#===============================================================================
""" GETOKEN - Put next token into the global TOKEN """
global token
ch = getch() # skip whitespace
while ch in ["\t", " ", "\n", "#"]:
ch = getch()
# If ch is alphabetic then this is start of reserved word or an identifier
if ch.isalpha(): # Letter therefore it's either identifier or reserved word
name = ""
while ch.isalpha() or ch.isdigit() or ch == "_":
name = name + ch
ch = getch()
ungetch() # let terminator be used next time
token = lookup(name) # See if token's known
if token is None: # if not
token = addToSymTbl(name, idsym) # add as 'idsym'-IDENTIFIER
return # we've set token.token to either id or tokentype of reserved word
#---------------------------------------------------------------------
# If it's numeric return TOKEN=number & token.value = binary value
elif ch.isdigit():
# In the real version, build number and don't forget to end with ungetch()
token = symbol(ch, number, value = int(ch)) # simplistic SINGLE DIGIT Ascii to Binary
return
#---------------------------------------------------------------------
# Single character tokens
elif ch in ["#", "<", ">", "{", "}", "(", ")", "+" , "-", "*", "/", ";","!", EOF]:
token = lookup(ch) # preloaded with appropriate token
elif ch in ["="]:
ch = getch()
char = "="
Equal = "=="
if ch == "=":
char = Equal
ch = getch()
else:
token = lookup(ch)
ungetch()
token = lookup(char)
if token is None:
token = addToSymTbl(char, idsym)
return
else:
print "Unknown character -->%s<- decimal %d" % (ch,ord(ch))
sys.exit(1) # Abort Compilation
#======================================================================
# THE GRAMMAR
# <program> ::= { <id> ; <vars > <stmtlist> }
# <vars> ::= var { <id> ; } % DECLARATIONS
# <stmtlist> ::= <stmt> { ; <stmt> }
# <stmt> ::= print <id>
# <id> = <expr>
# <expr> ::= <factor> { (+ | -) <factor> } % No precedence
# <factor> ::= ID | Number
#======================================================================
# Centralised Parser Error Message handler
#======================================================================
#===============================================================================
def error (msg):
#===============================================================================
print line
print "-" * charIndex,"^"
print("Error on %d - %s\n" % (number, msg))
printToken(token)
print("\n")
#===============================================================================
def emit (memadr, opcode, parameter):
#===============================================================================
"""EMIT CODE - Emit a of code with a Parameter
if first arg is zero - (the memory address), use and incr CODEPTR"""
global codeptr
if (memadr == 0):
memadr = codeptr
codeptr = codeptr+1
print "%6d %-8s %-7s" % (memadr, opcode, parameter)
#======================================================================
# VARIABLE DECLARATIONS
# <vars> ::= V { <id> ; }
#===============================================================================
def vars() :
#===============================================================================
global varptr;
getoken(); #skip VARSYM - already been recognised
while (token.token == idsym):
if token.address != 0:
print("%c already declared\n", token.name);
else:
symtbl[token.name].address = varptr;
varptr = varptr +1
getoken(); #skip past identifier
if token.token == semicolon: getoken() #skip ;
else: error("semicolon expected in declaration")
#======================================================================
# STMTLIST
# <stmtlist> ::= <stmt> { ; <stmt> }
#===============================================================================
def stmtList():
#===============================================================================
stmt()
while (token.token == semicolon):
getoken() #skip ;
stmt()
#======================================================================
# STMT
#===============================================================================
def stmt():
#===============================================================================
""" <stmt> ::= print <expression> | <id> = <expression> | if <expression> | while <expression>
"""
global codeptr
# thisStmtAdr = codeptr # Jump DEMO - not part of Stmt
if token.token == printsym:
printStmt()
elif token.token == idsym:
assignStmt()
elif token.token == ifsym:
ifStmt()
elif token.token == elsesym:
elseStmt()
elif token.token == whilesym:
whileStmt()
elif token.token == readint:
readIntStmt()
elif token.token == readch:
readChStmt()
elif token.token == writeint:
writeIntStmt()
elif token.token == writech:
writeChStmt()
elif token.token == rightbrace:
print("\n#*** Compilation finished ***\n")
else:
error("Expected start of a statement")
# emit (0, "return", thisStmtAdr) # Jump DEMO
#===============================================================================
def printStmt():
#===============================================================================
""" <printStmt> ::= print <expression>"""
getoken() # skip "print"
expression() # on return, expr result (at runtime) will be in ACC
emit(0, "writeint", 0) # Memory address 0 is the ACC
if token.token == rightbrace:
print("\n#*** Compilation finished ***\n")
#===============================================================================
def assignStmt():
#===============================================================================
"""
<id> = <expression>
"""
whichidentifier = token # Remember which ID on Left
getoken() # Get token after identifier
if token.token == assignsym:
getoken()
elif token.token == jumpeq:
getoken()
else:
error("Expected = in assignment statement")
expression()
# Save result into LHS runtime address
#===============================================================================
def ifStmt():
#if-then-else
#===============================================================================
""" <ifStmt> ::= if <expression>"""
getoken() # skip "if"
if token.token == idsym:getoken()
if token.token == assignsym: getoken()
if token.token == number:
emit(0, "loadv", token.value)
if token.token == semicolon:getoken()
#===============================================================================
def elseStmt():
#if-then-else
#===============================================================================
""" <elseStmt> ::= else <expression>"""
getoken()
if token.token == idsym: getoken()
if token.token == assignsym:getoken()
if token.token == idsym: getoken()
if token.token == plus: getoken()
if token.token == number:
emit(0, "loadv", token.value)
emit(0, "store", 400)
emit(0, "add", 202)
getoken()
emit(0, "jump", 20)
# emit(0, "increment", 1)
#emit(0, "store", 202)
# emit(0, "jumpi", 14)
#===============================================================================
def whileStmt():
#===============================================================================
""" <whileStmt> ::= while (condition)statement"""
getoken() # skip "if"
expression()
stmt()
# emit(0, "increment", 1)
# emit(0, "jumpi", 14)
#===============================================================================
def readIntStmt():
#===============================================================================
getoken()
expression() # skip "if"
emit(0, "readint",999)
#===============================================================================
def readChStmt():
#===============================================================================
getoken() # skip "if"
emit(0, "readch",11)
#===============================================================================
def writeIntStmt():
#===============================================================================
getoken() # skip "if"
expression()
emit(0, "writeint",50)
#===============================================================================
def writeChStmt():
#===============================================================================
getoken() # skip "if"
emit(0, "writech",51)
#===============================================================================
def expression():
#===============================================================================
"""
Leaves result in ACC at runtime
Use addresses 999 & 998 as Temporary variables
<expression> ::= <factor> { (+ | - | * | /) <factor> }
"""
factor()
while token.token == plus or token.token == minus or token.token == mpy or token.token == div or token.token == lessthan or token.token == greaterthan or token.token == jumpne or token.token == jumpeq:
op = token # remember +/-
getoken() # skip past +/-
emit(0, "store", 300) # Save current result
factor() # Evaluate next factor
#working
if op.token == plus:
emit(0, "loadv", 999)
emit(0, "add", 999)
emit(0, "store", 999)
if op.token == leftbracket:getoken()
elif op.token == minus: # Subtract - have to swap operand order
emit(0, "store", 998)
emit(0, "load" , 999)
emit(0, "subtract", 998) # Leaves result in Acc
emit(0, "store", 6)
elif op.token == mpy:
emit(0, "store", 998)
emit(0, "load", 999)
emit(0, "mpy", 998)
emit(0, "store", 7)
elif op.token == div:
emit(0, "store", 998)
emit(0, "load", 999)
emit(0, "div", 998)
emit(0, "store", 8)
elif op.token == lessthan:
emit(0, "store", 998)
emit(0, "compare", 999)
emit(0, "jumplt", 80)
emit(0, "loadv", 0)
emit(0, "store", 9)
elif op.token == greaterthan:
emit(0, "compare", 202)
emit(0, "jumpgt", 81)
getoken()
emit(81, "loadv", 2)
emit(82, "store", 202)
getoken()
elif op.token == jumpeq:
emit(0, "store", 998)
emit(0, "compare", 999)
emit(0, "jumpeq", 83)
#===============================================================================
def factor():
#===============================================================================
"""
# FACTOR() - leaves result in ACC at runtime
<factor> ::= (+|-) identifier | number
"""
#Numbers
if token.token == idsym:
emit(0, "load", token.address)
getoken()
elif token.token == number:
emit(0, "loadv", token.value)
emit(0, "store", 200+token.value)
getoken()
else: error("Start of Factor expected")
#===============================================================================
def program():
#===============================================================================
""" # PROGRAM - Start production of the grammar
# <program> ::= { <id> ; <vars > <stmtlist> }
"""
if token.token == leftbrace: getoken()
else: error(" { expected")
if token.token == idsym: getoken()
else: error("Program name expected")
if token.token == semicolon: getoken()
else: error("Semicolon expected")
if token.token == varsym : vars()
stmtList()
if token.token == elsesym:elseStmt()
stmtList()
if token.token == rightbrace:
print("\n#*** Compilation finished ***\n")
else: error(" } expected")
# Compiler main function
#======================================================================
def main():
#======================================================================
global line
global srcfile
global outfile
global charIndex
initSymTbl()
# srcfile = open('while_If_forever_loop.txt', 'r')
# srcfile = open('while_If_Continue_restart_loop.txt', 'r')
srcfile = open('while_If_Continue_restart_loop.txt', 'r')
line = srcfile.read() # readline
# for line in open('tiny.txt', 'r'):
# if not line.startswith("#"):
# debugScanner = False
charIndex = 0
debugScanner = False
if debugScanner: # Scanner Test Routine - Read a line and display the tokens
getoken()
while token.token is not None: # Skeleton for testing Scanner
printToken(token)
# outfile.write(token)
getoken()
sys.exit(1)
else:
getoken() # Parse Program according to the grammar
program() # Call start non-terminal handler
#===============================================================================
# Main Compiler starts here
#===============================================================================
print "#Microcompiler.py v0.2"
emit(0, "load", 0)
#emit(0, "constant", "'A'")
#emit(0, "constant", 10)
#emit(0, "constant", 12)
#emit(0, "constant", 25)
#emit(0, "constant", -10)
main()
#srcfile = open('tiny.txt', 'r')
#lexer = shlex.shlex(srcfile)
#for token in lexer:
# print repr(token)
#getoken()
| [
[
8,
0,
0.0132,
0.0186,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0248,
0.0016,
0,
0.66,
0.0238,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.0264,
0.0016,
0,
0.66... | [
"\"\"\" Giovanni's MicroCompiler Demo\n\n<program> ::= { <id> ; <vars > <stmtlist> }\n<vars> ::= V { <id> ; } % DECLARATIONS\n\n<stmtlist> ::= <stmt> { ; <stmt> }\n<stmt> ::= P <id> | <id> = <expr>",
"import sys",
"import shlex",
"tokenName... |
""" Giovanni's MicroCompiler Demo
<program> ::= { <id> ; <vars > <stmtlist> }
<vars> ::= V { <id> ; } % DECLARATIONS
<stmtlist> ::= <stmt> { ; <stmt> }
<stmt> ::= P <id> | <id> = <expr>
<expr> ::= <factor> { (+ | -) <factor> } % No precedence
<factor> ::= (+|-) ID | Number
"""
import sys
import shlex
#===============================================================================
# # Lexical Analyser - the "Scanner" - Define the TokenTypes
#===============================================================================
tokenNames =\
[ "unknownToken", "idsym", "assignsym", "leftbrace", "rightbrace",
"varsym", "semicolon", "whilesym", "leftbracket", "rightbracket",
"printsym", "ifsym", "elsesym", "equals", "notequals", "lessthan", "greaterthan",
"readch", "readint", "writech", "writeint",
"number", "plus", "minus", "mpy", "div", "jumpne", "jumpeq","lessthanequal","greaterthanequal","remainder", "endfile"]
# define the tokens as variables
unknownToken, idsym, assignsym, leftbrace, rightbrace,\
varsym, semicolon, whilesym, leftbracket, rightbracket,\
printsym, ifsym, elsesym, equals, notequals, lessthan, greaterthan,\
readch, readint, writech, writeint,\
number, plus, minus, mpy, div, jumpne, jumpeq, lessthanequal, greaterthanequal,remainder, endfile = range(0, len(tokenNames))
#===============================================================================
class symbol:
#===============================================================================
name = None # String representation
token = None; # Corresponding token
address = 0; # For variables, their runtime address
value = None # on defined for numbers
def __init__(self, name, token, value = 0):
self.name = name
self.token = token
self.address = 0 # for identifiers, their address
self.value = value # for numbers, their value
symtbl = {}; # The Symbol Table, a dictionary of symbols indexed by name
#======================================================================
# GLOBALS for output of Lexical Analyser
# Set by each call to GeToken()
token = None; # A symbol
line = "\n" # the complex source file as a string
charIndex = 0 # the position in the source
linenumber= 0 # The current number
EOF = chr(0)
#======================================================================
# Run Time Code Generation Variables
varptr = 500 # Arbitrary base address of memory for variables
codeptr = 10 # Address to output next instruction (for code)
#===============================================================================
# Symbol Table Management Routines
#===============================================================================
#===============================================================================
def addToSymTbl (name, token):
#===============================================================================
symtbl[name] = symbol(name, token) # Add a new symbol to the dictionary
return symtbl[name]
#===============================================================================
def lookup (thisName):
#===============================================================================
"# Find a given identifier in the Symbol Table, Return the symtbl entry"
if symtbl.has_key(thisName): # thisName has been seen before
return symtbl[thisName] # return the symtbl entry
else: return None
#===============================================================================
def initSymTbl():
#===============================================================================
"# Initialise Symbol Table, and preload reserved words"
addToSymTbl('var', varsym) # VAR
addToSymTbl('while', whilesym) # WHILE
addToSymTbl('for', whilesym) # WHILE
addToSymTbl('print', printsym) # PRINT
addToSymTbl('if', ifsym) # IF
addToSymTbl('else', elsesym) # ELSE
addToSymTbl('readint', readint) #READINT
addToSymTbl('writeint', writeint) #READINT
addToSymTbl('readch', readch) #READINT
addToSymTbl('writech', writech) #READINT
# Now add symbols - NB only single character symbols are here
# multicharacter one like ">=" are still to do
addToSymTbl( '=', assignsym)
addToSymTbl( '#', notequals)
addToSymTbl( '<', lessthan) #jumplt
addToSymTbl( '>', greaterthan) #jumpgt
addToSymTbl( '{', leftbrace )
addToSymTbl( '}', rightbrace)
addToSymTbl( '(', leftbracket)
addToSymTbl( ')', rightbracket)
addToSymTbl( '+', plus )
addToSymTbl( '-', minus)
addToSymTbl( '*', mpy)
addToSymTbl( '/', div)
addToSymTbl( ';', semicolon)
addToSymTbl( '%', remainder)
addToSymTbl( EOF, endfile)
#multicharacter one like ">=" are still to do
addToSymTbl( '!=', jumpne)
addToSymTbl( '==', jumpeq)
addToSymTbl( '<=', lessthanequal) #jumplt
addToSymTbl( '>=', greaterthanequal) #jumpgt
#===============================================================================
# Scanner Diagnostics
#===============================================================================
def printToken(tok):
#===============================================================================
" - display the specified token."
if tok.token == idsym:
print "Token = %10s, %-10s adr = %3d" %\
(tokenNames[tok.token], tok.name, tok.address)
elif tok.token == number:
print "Token = %10s %d" % (tokenNames[tok.token], tok.value)
else:
print "Token = %10s" % tokenNames[tok.token]
#==============================?=================================================
def dumpSymTbl():
#===============================================================================
""" Dump all the tokens in the symboltable """
print(" *** Symbol Table ***")
for name in symtbl.keys(): # keys is a list of the names (printable form of tokens)
tok = symtbl[name]
if tok.token == idsym:
printToken(tok)
#===============================================================================
def getch():
#===============================================================================
global line
global charIndex
global linenumber
while True:
if charIndex < len(line): # See if used up current line
ch = line[charIndex] # if not, get character
charIndex = charIndex+1 # & move pointer for next time
else:
#line = srcfile.readline()
if line == "": line = EOF
#print "--> ",
line = raw_input() +"\n" # read new line, adding \n so it's like f.readline()
charIndex = 0 # & reset character pointer
linenumber = linenumber + 1
continue
if ch == "\n":
ch = " " # A newline is a token separator
if ch == "?":
dumpSymTbl()
continue
if ch == "#":
print "#Comment Found"
srcfile.read()
print "#Read next line"
return ch
#===============================================================================
def ungetch():
#===============================================================================
""" Unget the next character peeked at when building variables, numbers
and when distinguishing between >= and > ...
"""
global charIndex;
charIndex = charIndex-1;
#===============================================================================
def getoken():
#===============================================================================
""" GETOKEN - Put next token into the global TOKEN """
global token
ch = getch() # skip whitespace
while ch in ["\t", " ", "\n", "#"]:
ch = getch()
# If ch is alphabetic then this is start of reserved word or an identifier
if ch.isalpha(): # Letter therefore it's either identifier or reserved word
name = ""
while ch.isalpha() or ch.isdigit() or ch == "_":
name = name + ch
ch = getch()
ungetch() # let terminator be used next time
token = lookup(name) # See if token's known
if token is None: # if not
token = addToSymTbl(name, idsym) # add as 'idsym'-IDENTIFIER
return # we've set token.token to either id or tokentype of reserved word
#---------------------------------------------------------------------
# If it's numeric return TOKEN=number & token.value = binary value
elif ch.isdigit():
# In the real version, build number and don't forget to end with ungetch()
token = symbol(ch, number, value = int(ch)) # simplistic SINGLE DIGIT Ascii to Binary
return
#---------------------------------------------------------------------
# Single character tokens
elif ch in ["#", "{", "}", "(", ")", "+" , "-", "*", "/", ";","%", EOF]:
token = lookup(ch) # preloaded with appropriate token
elif ch in ["!"]:
ch = getch()
char = "!"
nEqual = "!="
if ch == "=":
char = nEqual
ch = getch()
else:
token = lookup(ch)
ungetch()
token = lookup(char)
if token is None:
token = addToSymTbl(char, idsym)
return
elif ch in ["="]:
ch = getch()
char = "="
Equal = "=="
if ch == "=":
char = Equal
ch = getch()
else:
token = lookup(ch)
ungetch()
token = lookup(char)
if token is None:
token = addToSymTbl(char, idsym)
return
elif ch in ["<"]:
ch = getch()
char = "<"
lessthanEqual = "<="
if ch == "=":
char = lessthanEqual
ch = getch()
else:
token = lookup(ch)
ungetch()
token = lookup(char)
if token is None:
token = addToSymTbl(char, idsym)
return
elif ch in [">"]:
ch = getch()
char = ">"
greatthanEqual = ">="
if ch == "=":
char = greatthanEqual
ch = getch()
else:
token = lookup(ch)
ungetch()
token = lookup(char)
if token is None:
token = addToSymTbl(char, idsym)
return
else:
print "Unknown character -->%s<- decimal %d" % (ch,ord(ch))
sys.exit(1) # Abort Compilation
#======================================================================
# THE GRAMMAR
# <program> ::= { <id> ; <vars > <stmtlist> }
# <vars> ::= var { <id> ; } % DECLARATIONS
# <array> ::= [<expr>]
# <stmtlist> ::= <stmt> { ; <stmt> }
# <stmt> ::= print <id>
# <id> = <expr>
# <expr> ::= <factor> { (+ | -) <factor> } % No precedence
# <factor> ::= [+/-] ID | Number
#======================================================================
# Centralised Parser Error Message handler
#======================================================================
#===============================================================================
def error (msg):
#===============================================================================
print line
print "-" * charIndex,"^"
print("Error on %d - %s\n" % (number, msg))
printToken(token)
print("\n")
#===============================================================================
def emit (memadr, opcode, parameter):
#===============================================================================
"""EMIT CODE - Emit a of code with a Parameter
if first arg is zero - (the memory address), use and incr CODEPTR"""
global codeptr
if (memadr == 0):
memadr = codeptr
codeptr = codeptr+1
print "%6d %-8s %-7s" % (memadr, opcode, parameter)
#======================================================================
# VARIABLE DECLARATIONS
# <vars> ::= V { <id> ; }
#===============================================================================
def vars() :
#===============================================================================
global varptr;
getoken(); #skip VARSYM - already been recognised
while (token.token == idsym):
if token.address != 0:
print("%c already declared\n", token.name);
else:
symtbl[token.name].address = varptr;
varptr = varptr +1
getoken(); #skip past identifier
if token.token == semicolon: getoken() #skip ;
else: error("semicolon expected in declaration")
#======================================================================
# STMTLIST
# <stmtlist> ::= <stmt> { ; <stmt> }
#===============================================================================
def stmtList():
#===============================================================================
stmt()
while (token.token == semicolon):
getoken() #skip ;
stmt()
#======================================================================
# STMT
#===============================================================================
def stmt():
#===============================================================================
""" <stmt> ::= print <expression> | <id> = <expression> | if <expression> | while <expression>
"""
global codeptr
# thisStmtAdr = codeptr # Jump DEMO - not part of Stmt
if token.token == printsym:
printStmt()
elif token.token == idsym:
assignStmt()
elif token.token == assignsym:
getoken()
elif token.token == ifsym:
ifStmt()
elif token.token == elsesym:
elseStmt()
elif token.token == whilesym:
whileStmt()
elif token.token == readint:
readIntStmt()
elif token.token == readch:
readChStmt()
elif token.token == writeint:
writeIntStmt()
elif token.token == writech:
writeChStmt()
elif token.token == jumpne:
expression()
elif token.token == jumpeq:
expression()
elif token.token == lessthanequal:
expression()
elif token.token == greaterthanequal:
expression()
elif token.token == rightbrace:getoken()
elif token.token == semicolon:
getoken()
else:
error("Expected start of a statement")
# emit (0, "return", thisStmtAdr) # Jump DEMO
#===============================================================================
def printStmt():
#===============================================================================
""" <printStmt> ::= print <expression>"""
getoken() # skip "print"
expression() # on return, expr result (at runtime) will be in ACC
emit(0, "writeint", 0) # Memory address 0 is the ACC
if token.token == rightbrace:
print("#\n*** Compilation finished ***\n")
#===============================================================================
def assignStmt():
#===============================================================================
"""
<id> = <expression>
"""
whichidentifier = token # Remember which ID on Left
getoken() # Get token after identifier
if token.token == notequals: # skip # then read next line
srcfile.read()
getoken()
elif token.token == assignsym: #if the next token is =
expression()
elif token.token == idsym: factor()
elif token.token == ifsym: stmt()
elif token.token == whilesym: stmt()
elif token.token == jumpeq: print("#")
elif token.token == jumpne: print("#")
elif token.token == lessthanequal: print("#")
elif token.token == greaterthanequal: print("#")
elif token.token == semicolon: getoken()
else:
error("Expected = in assignment statement")
expression()
# Save result into LHS runtime address
#===============================================================================
def ifStmt():
#if-then-else
#===============================================================================
""" <ifStmt> ::= if <expression>"""
getoken() # skip "if"
expression()
stmt()
#===============================================================================
def elseStmt():
#if-then-else
#===============================================================================
""" <elseStmt> ::= else <expression>"""
getoken()
emit(0, "store", 888)
stmt()
#===============================================================================
def whileStmt():
#===============================================================================
""" <whileStmt> ::= while (condition)statement"""
print("#While statement\n")
getoken() # skip "while"
expression()
emit(0, "compare", 204)
stmt()
emit(0, "increment", 1)
emit(0, "jumpi", 14)
#===============================================================================
def readIntStmt():
#===============================================================================
getoken()
expression()
emit(0, "readint",999)
#===============================================================================
def readChStmt():
#===============================================================================
getoken()
emit(0, "readch",11)
#===============================================================================
def writeIntStmt():
#===============================================================================
getoken() # skip "if"
expression()
emit(0, "writeint",50)
#===============================================================================
def writeChStmt():
#===============================================================================
getoken() # skip "if"
emit(0, "writech",51)
#===============================================================================
def expression():
#===============================================================================
"""
Leaves result in ACC at runtime
Use addresses 999 & 998 as Temporary variables
<expression> ::= <factor> { (+ | - | * | /) <factor> }
"""
factor()
while token.token == plus or token.token == minus or token.token == mpy or token.token == div or token.token == lessthan or token.token == greaterthan or token.token == jumpeq or token.token == jumpne or token.token == lessthanequal or token.token == greaterthanequal:
op = token # remember +/-
getoken() # skip past +/-
#emit(0, "store", 2) # Save current result
factor() # Evaluate next factor
#working
if op.token == plus: #+
emit(0, "loadv", 999)
emit(0, "add", 999)
emit(0, "store", 999)
elif op.token == minus: # - Subtract - have to swap operand order
emit(0, "store", 998)
emit(0, "load" , 999)
emit(0, "subtract", 998) # Leaves result in Acc
emit(0, "store", 880)
elif op.token == mpy: #*
emit(0, "store", 998)
emit(0, "load", 999)
emit(0, "mpy", 998)
emit(0, "store", 881)
elif op.token == div: #/
emit(0, "store", 998)
emit(0, "load", 999)
emit(0, "div", 998)
emit(0, "store", 882)
elif op.token == remainder: #%
emit(0, "store", 998)
emit(0, "load", 999)
emit(0, "mod", 998)
emit(0, "store", 883)
elif op.token == jumpeq: #==
print("#==\n")
emit(0, "compare", 11)
emit(0, "jumpeq", 310)
if token.token == idsym:getoken()
if token.token == assignsym:getoken()
emit(310, "loadv", token.value)
emit(311, "store", 401)
emit(312, "return", 0)
getoken()
getoken()
elif op.token == jumpne: #!=
print("#!=\n")
emit(0, "compare", 204)
emit(0, "jumpne", 300)
if token.token == idsym:getoken()
if token.token == assignsym:getoken()
emit(300, "loadv", token.value)
emit(301, "store", 400)
emit(302, "return", 0)
getoken()
getoken()
elif op.token == lessthanequal: #<=
print("#<=\n")
emit(0, "compare", 204)
emit(0, "jumplt", 320)
emit(0, "compare", 204)
emit(0, "jumpeq", 320)
if token.token == idsym:getoken()
if token.token == assignsym:getoken()
emit(320, "loadv", token.value)
emit(321, "store", 402)
emit(322, "return", 0)
getoken()
getoken()
elif op.token == greaterthanequal: #>=
print("#>=\n")
emit(0, "compare", 204)
emit(0, "jumpgt", 330)
emit(0, "compare", 204)
emit(0, "jumpeq", 330)
if token.token == idsym:getoken()
if token.token == assignsym:getoken()
emit(330, "loadv", token.value)
emit(331, "store", 403)
emit(332, "return", 0)
getoken()
if token.token == semicolon:getoken()
#===============================================================================
def factor():
#===============================================================================
"""
# FACTOR() - leaves result in ACC at runtime
<factor> ::= (+|-) identifier | number
"""
#Numbers
if token.token == idsym:
emit(0, "load", token.address)
getoken()
elif token.token == number:
emit(0, "loadv", token.value)
emit(0, "store", 200+token.value)
getoken()
elif token.token == assignsym:getoken()
elif token.token == jumpeq:
print("#==")
elif token.token == jumpne:
print("")
elif token.token == lessthanequal:
print("#<=")
elif token.token == greaterthanequal:
print("#<=")
elif token.token == lessthan:
print("#<")
elif token.token == ifsym:
ifStmt()
elif token.token == elsesym:
elseStmt()
elif token.token == whilesym:
whileStmt()
elif token.token == semicolon: getoken()
else: error("Start of Factor expected")
#===============================================================================
def program():
#===============================================================================
""" # PROGRAM - Start production of the grammar
# <program> ::= { <id> ; <vars > <stmtlist> }
"""
if token.token == leftbrace: getoken()
else: error(" { expected")
if token.token == idsym: getoken()
else: error("Program name expected")
if token.token == semicolon: getoken()
else: error("Semicolon expected")
if token.token == varsym : vars()
stmtList()
if token.token == rightbrace:
print("\n")
else: error(" } expected")
if token.token == rightbrace:
print("\n")
# Compiler main function
#======================================================================
def main():
#======================================================================
global line
global srcfile
global outfile
global charIndex
initSymTbl()
srcfile = open('character.txt', 'r')
line = srcfile.read() # readline
# for line in open('tiny.txt', 'r'):
# if not line.startswith("#"):
# debugScanner = False
charIndex = 0
debugScanner = False
if debugScanner: # Scanner Test Routine - Read a line and display the tokens
getoken()
while token.token is not None: # Skeleton for testing Scanner
printToken(token)
# outfile.write(token)
getoken()
srcfile.close()
sys.exit(1)
else:
getoken() # Parse Program according to the grammar
program() # Call start non-terminal handler
#===============================================================================
# Main Compiler starts here
#===============================================================================
print "#Microcompiler.py v0.2"
emit(0, "load", 0)
main()
#srcfile = open('tiny.txt', 'r')
#lexer = shlex.shlex(srcfile)
#for token in lexer:
# print repr(token)
getoken()
| [
[
8,
0,
0.0115,
0.0163,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0217,
0.0014,
0,
0.66,
0.0233,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.0231,
0.0014,
0,
0.66... | [
"\"\"\" Giovanni's MicroCompiler Demo\n\n<program> ::= { <id> ; <vars > <stmtlist> }\n<vars> ::= V { <id> ; } % DECLARATIONS\n\n<stmtlist> ::= <stmt> { ; <stmt> }\n<stmt> ::= P <id> | <id> = <expr>",
"import sys",
"import shlex",
"tokenName... |
'''
Created on Jun 23, 2014
@author: Brian
'''
""" Giovanni's MicroCompiler Demo
<program> ::= { <id> ; <vars > <stmtlist> }
<vars> ::= V { <id> ; } % DECLARATIONS
<stmtlist> ::= <stmt> { ; <stmt> }
<stmt> ::= P <id> | <id> = <expr>
<expr> ::= <factor> { (+ | -) <factor> } % No precedence
<factor> ::= (+|-) ID | Number
"""
import sys
import shlex
#===============================================================================
# # Lexical Analyser - the "Scanner" - Define the TokenTypes
#===============================================================================
tokenNames =\
[ "unknownToken","programsym", "idsym", "assignsym", "leftbrace", "rightbrace","comma",
"varsym","functionsym", "semicolon", "whilesym", "leftbracket", "rightbracket",
"printsym","printmsg", "ifsym", "elsesym","declaresym","forsym", "equals", "notequals", "lessthan", "greaterthan",
"readch", "readint", "writech", "writeint","addup","addup_1",
"number", "plus", "minus", "mpy", "div", "jumpne", "jumpeq","lessthanequal","greaterthanequal","ex","remainder","returnvalue","return_a", "endfile"]
# define the tokens as variables
unknownToken,programsym, idsym, assignsym, leftbrace, rightbrace, comma,\
varsym,functionsym, semicolon, whilesym, leftbracket, rightbracket,\
printsym,printmsg, ifsym, elsesym,declaresym, forsym, equals, notequals, lessthan, greaterthan,\
readch, readint, writech, writeint, addup,addup_1,\
number, plus, minus, mpy, div, jumpne, jumpeq, lessthanequal, greaterthanequal,ex,remainder,returnvalue,return_a, endfile = range(0, len(tokenNames))
#===============================================================================
class symbol:
#===============================================================================
name = None # String representation
token = None; # Corresponding token
address = 0; # For variables, their runtime address
value = None # on defined for numbers
def __init__(self, name, token, value = 0):
self.name = name
self.token = token
self.address = 0 # for identifiers, their address
self.value = value # for numbers, their value
symtbl = {}; # The Symbol Table, a dictionary of symbols indexed by name
#======================================================================
# GLOBALS for output of Lexical Analyser
# Set by each call to GeToken()
token = None; # A symbol
line = "\n" # the complex source file as a string
charIndex = 0 # the position in the source
linenumber= 0 # The current number
EOF = chr(0)
#======================================================================
# Run Time Code Generation Variables
varptr = 500 # Arbitrary base address of memory for variables
codeptr = 10 # Address to output next instruction (for code)
#===============================================================================
# Symbol Table Management Routines
#===============================================================================
#===============================================================================
def addToSymTbl (name, token):
#===============================================================================
symtbl[name] = symbol(name, token) # Add a new symbol to the dictionary
return symtbl[name]
#===============================================================================
def lookup (thisName):
#===============================================================================
"# Find a given identifier in the Symbol Table, Return the symtbl entry"
if symtbl.has_key(thisName): # thisName has been seen before
return symtbl[thisName] # return the symtbl entry
else: return None
#===============================================================================
def initSymTbl():
#===============================================================================
"# Initialise Symbol Table, and preload reserved words"
addToSymTbl('var', varsym) # VAR
addToSymTbl('function', functionsym) # function
addToSymTbl('program', programsym) # function
addToSymTbl('declare', declaresym)
addToSymTbl('while', whilesym) # WHILE
addToSymTbl('for', forsym) # WHILE
addToSymTbl('print', printsym) # PRINT
addToSymTbl('printmsg', printmsg)#PRINTMESSAGE
addToSymTbl('if', ifsym) # IF
addToSymTbl('else', elsesym) # ELSE
addToSymTbl('readint', readint) #READINT
addToSymTbl('writeint', writeint) #READINT
addToSymTbl('readch', readch) #READINT
addToSymTbl('writech', writech) #READINT
addToSymTbl('addup', addup)#ADDUP
addToSymTbl('addup(1)',addup_1)
# Now add symbols - NB only single character symbols are here
# multicharacter one like ">=" are still to do
addToSymTbl( '=', assignsym)
addToSymTbl( '#', notequals)
addToSymTbl( '<', lessthan) #jumplt
addToSymTbl( '>', greaterthan) #jumpgt
addToSymTbl( '{', leftbrace )
addToSymTbl( '}', rightbrace)
addToSymTbl( '(', leftbracket)
addToSymTbl( ')', rightbracket)
addToSymTbl( '+', plus )
addToSymTbl( '-', minus)
addToSymTbl( '*', mpy)
addToSymTbl( '/', div)
addToSymTbl( ';', semicolon)
addToSymTbl( '!', ex)
addToSymTbl( '%', remainder)
addToSymTbl( ',', comma)
addToSymTbl( EOF, endfile)
#multicharacter one like ">=" are still to do
addToSymTbl( '==', jumpeq)
addToSymTbl( '!=', jumpne)
addToSymTbl( '<=', lessthanequal) #jumplt
addToSymTbl( '>=', greaterthanequal) #jumpgt
addToSymTbl( 'return', returnvalue)
addToSymTbl( 'return a', return_a)
#===============================================================================
# Scanner Diagnostics
#===============================================================================
def printToken(tok):
#===============================================================================
" - display the specified token."
if tok.token == idsym:
print "Token = %10s, %-10s adr = %3d" %\
(tokenNames[tok.token], tok.name, tok.address)
elif tok.token == number:
print "Token = %10s %d" % (tokenNames[tok.token], tok.value)
else:
print "Token = %10s" % tokenNames[tok.token]
#==============================?=================================================
def dumpSymTbl():
#===============================================================================
""" Dump all the tokens in the symboltable """
print(" *** Symbol Table ***")
for name in symtbl.keys(): # keys is a list of the names (printable form of tokens)
tok = symtbl[name]
if tok.token == idsym:
printToken(tok)
#===============================================================================
def getch():
#===============================================================================
global line
global charIndex
global linenumber
while True:
if charIndex < len(line): # See if used up current line
ch = line[charIndex] # if not, get character
charIndex = charIndex+1 # & move pointer for next time
else:
#line = srcfile.readline()
if line == "": line = EOF
#print "--> ",
line = raw_input() +"\n" # read new line, adding \n so it's like f.readline()
charIndex = 0 # & reset character pointer
linenumber = linenumber + 1
continue
if ch == "\n":
ch = " " # A newline is a token separator
if ch == "?":
dumpSymTbl()
continue
if ch == "#":
print "#Comment Found"
srcfile.read()
print "#Read next line"
return ch
#===============================================================================
def ungetch():
#===============================================================================
""" Unget the next character peeked at when building variables, numbers
and when distinguishing between >= and > ...
"""
global charIndex;
charIndex = charIndex-1;
#===============================================================================
def getoken():
#===============================================================================
""" GETOKEN - Put next token into the global TOKEN """
global token
ch = getch() # skip whitespace
while ch in ["\t", " ", "\n", "#"]:
ch = getch()
# If ch is alphabetic then this is start of reserved word or an identifier
if ch.isalpha(): # Letter therefore it's either identifier or reserved word
name = ""
while ch.isalpha() or ch.isdigit() or ch == "_":
name = name + ch
ch = getch()
ungetch() # let terminator be used next time
token = lookup(name) # See if token's known
if token is None: # if not
token = addToSymTbl(name, idsym) # add as 'idsym'-IDENTIFIER
return # we've set token.token to either id or tokentype of reserved word
#---------------------------------------------------------------------
# If it's numeric return TOKEN=number & token.value = binary value
elif ch.isdigit():
# In the real version, build number and don't forget to end with ungetch()
token = symbol(ch, number, value = int(ch)) # simplistic SINGLE DIGIT Ascii to Binary
return
#---------------------------------------------------------------------
# Single character tokens
elif ch in [",", "{", "}", "(", ")", "+" , "-", "*", "/", ";","%", EOF]:
token = lookup(ch) # preloaded with appropriate token
# special characters
# check ==
elif ch in ["!"]:
ch = getch()
char = "!"
nEqual = "!="
if ch == "=":
char = nEqual
ch = getch()
else:
token = lookup(ch)
ungetch()
token = lookup(char)
if token is None:
token = addToSymTbl(char, idsym)
return
# check ==
elif ch in ["="]:
ch = getch()
char = "="
Equal = "=="
if ch == "=":
char = Equal
ch = getch()
else:
token = lookup(ch)
ungetch()
token = lookup(char)
if token is None:
token = addToSymTbl(char, idsym)
return
# check <=
elif ch in ["<"]:
ch = getch()
char = "<"
lessthanEqual = "<="
if ch == "=":
char = lessthanEqual
ch = getch()
else:
token = lookup(ch)
ungetch()
token = lookup(char)
if token is None:
token = addToSymTbl(char, idsym)
return
# check >=
elif ch in [">"]:
ch = getch()
char = ">"
greatthanEqual = ">="
if ch == "=":
char = greatthanEqual
ch = getch()
else:
token = lookup(ch)
ungetch()
token = lookup(char)
if token is None:
token = addToSymTbl(char, idsym)
return
elif ch in ["addup"]:
ch = getch()
addup_a = "addup(a)"
if ch == "(":
ch = getch()
if ch == "a":
ch = getch()
if ch == ")":
char = addup_a
else:
token = lookup(ch)
else:
token = lookup(ch)
else:
token = lookup(ch)
ungetch()
token = lookup(char)
if token is None:
token = addToSymTbl(char, idsym)
return
elif token.token ==return_a:
emit(0,"return", 0)
getoken()
else:
print "Unknown character -->%s<- decimal %d" % (ch,ord(ch))
sys.exit(1) # Abort Compilation
#======================================================================
# THE GRAMMAR
# <program> ::= { <id> ; <vars > <stmtlist> }
# <vars> ::= var { <id> ; } % DECLARATIONS
# <array> ::= [<expr>]
# <stmtlist> ::= <stmt> { ; <stmt> }
# <stmt> ::= print <id>
# <id> = <expr>
# <expr> ::= <factor> { (+ | -) <factor> } % No precedence
# <factor> ::= [+/-] ID | Number
#======================================================================
# Centralised Parser Error Message handler
#======================================================================
#===============================================================================
def error (msg):
#===============================================================================
print line
print "-" * charIndex,"^"
print("Error on %d - %s\n" % (number, msg))
printToken(token)
print("\n")
#===============================================================================
def emit (memadr, opcode, parameter):
#===============================================================================
"""EMIT CODE - Emit a of code with a Parameter
if first arg is zero - (the memory address), use and incr CODEPTR"""
global codeptr
if (memadr == 0):
memadr = codeptr
codeptr = codeptr+1
print "%6d %-8s %-7s" % (memadr, opcode, parameter)
#======================================================================
# VARIABLE DECLARATIONS
# <vars> ::= V { <id> ; }
#===============================================================================
def vars() :
#===============================================================================
global varptr;
getoken(); #skip VARSYM - already been recognised
while (token.token == idsym):
if token.address != 0:
print("%c already declared\n", token.name);
else:
symtbl[token.name].address = varptr;
varptr = varptr +1
getoken(); #skip past identifier
if token.token == semicolon: getoken() #skip ;
elif token.token == assignsym: getoken()
else: error("semicolon expected in declaration")
#===============================================================================
def parameters(value1):
#<parameters> ::= (<value>)
#===============================================================================
global va1;
if token.token == leftbracket:getoken();
#1st variable
if token.token == number:
emit(0, "loadv", token.value)
if token.token == rightbracket: getoken();
#======================================================================
# STMTLIST
# <stmtlist> ::= <stmt> { ; <stmt> }
#===============================================================================
def stmtList():
#===============================================================================
stmt()
while (token.token == semicolon):
getoken() #skip ;
stmt()
#======================================================================
# STMT
#===============================================================================
def stmt():
#===============================================================================
""" <stmt> ::= print <expression> | <id> = <expression> | if <expression> | while <expression>
"""
global codeptr
# thisStmtAdr = codeptr # Jump DEMO - not part of Stmt
if token.token == printsym:
printStmt()
elif token.token == printmsg:
printMsg()
elif token.token == addup:
addup()
elif token.token == idsym:
assignStmt()
elif token.token == assignsym:
getoken()
elif token.token == varsym:
vars()
elif token.token == ifsym:
ifStmt()
elif token.token == elsesym:
elseStmt()
elif token.token == whilesym:
whileStmt()
elif token.token == readint:
readIntStmt()
elif token.token == readch:
readChStmt()
elif token.token == writeint:
writeIntStmt()
elif token.token == writech:
writeChStmt()
elif token.token == functionsym:
functionStmt()
elif token.token == rightbrace:
print("")
elif token.token == semicolon:
print("")
else:
error("Expected start of a statement")
# emit (0, "return", thisStmtAdr) # Jump DEMO
#===============================================================================
def printStmt():
#===============================================================================
""" <printStmt> ::= print <expression>"""
getoken() # skip "print"
expression() # on return, expr result (at runtime) will be in ACC
emit(0, "writeint", 0) # Memory address 0 is the ACC
if token.token == rightbrace:
print("#\n*** Compilation finished ***\n")
#===============================================================================
def printMsg():
#===============================================================================
""" <printMsg> ::= printMsg <expression>"""
print("#Print String APPLE to memory")
emit(0, "loadv", 100)
emit(0, "store", 1)
emit(0, "call", 40)
emit(40, "load-Ind", 0)
emit(41, "jumpeq", 45)
emit(42, "writech",150)
emit(43, "increment", 1)
emit(44, "jump", 40)
emit(45, "return", 0)
#===============================================================================
def assignStmt():
#===============================================================================
"""
<id> = <expression>
"""
whichidentifier = token # Remember which ID on Left
getoken() # Get token after identifier
if token.token == notequals: # skip # then read next line
srcfile.read()
getoken()
elif token.token == assignsym: #if the next token is =
expression()
elif token.token == idsym: factor()
elif token.token == jumpeq: print("#")
elif token.token == jumpne: print("#")
elif token.token == lessthanequal: print("")
elif token.token == greaterthanequal: print("")
elif token.token == semicolon: getoken()
else:
error("Expected = in assignment statement")
expression()
# Save result into LHS runtime address
#===============================================================================
def ifStmt():
#if-then-else
#===============================================================================
""" <ifStmt> ::= if <expression>"""
getoken() # skip "if"
emit(0, "compare",60)
expression()
stmt()
emit(0, "return",0)
#===============================================================================
def elseStmt():
#if-then-else
#===============================================================================
""" <elseStmt> ::= else <expression>"""
getoken()
emit(0, "store", 888)
stmt()
#===============================================================================
def whileStmt():
#===============================================================================
""" <whileStmt> ::= while (condition)statement"""
getoken() # skip "if"
emit(0, "compare",50)
expression()
stmt()
emit(0, "increment", 1)
emit(0, "jumpi", 14)
#===============================================================================
def readIntStmt():
#===============================================================================
getoken()
expression() # skip "if"
emit(0, "readint",999)
#===============================================================================
def readChStmt():
#===============================================================================
getoken() # skip "if"
emit(0, "readch",11)
#===============================================================================
def writeIntStmt():
#===============================================================================
getoken() # skip "if"
expression()
emit(0, "writeint",50)
#===============================================================================
def writeChStmt():
#===============================================================================
getoken() # skip "if"
emit(0, "writech",51)
#===============================================================================
def expression():
#===============================================================================
"""
Leaves result in ACC at runtime
Use addresses 999 & 998 as Temporary variables
<expression> ::= <factor> { (+ | - | * | /) <factor> }
"""
factor()
while token.token == plus or token.token == minus:
op = token # remember +/-
getoken() # skip past +/-
emit(0, "store", 1) # Save current result
factor() # Evaluate next factor
#working
if op.token == plus: #+
emit(0, "call", 27)
elif op.token == minus: # - Subtract - have to swap operand order
emit(0, "store", 998)
emit(0, "load" , 999)
emit(0, "subtract", 998) # Leaves result in Acc
emit(0, "store", 880)
#===============================================================================
def factor():
#===============================================================================
"""
# FACTOR() - leaves result in ACC at runtime
<factor> ::= (+|-) identifier | number
"""
#Numbers
if token.token == idsym:
emit(0, "load", token.address)
getoken()
elif token.token == number:
emit(0, "loadv", token.value)
getoken()
elif token.token == assignsym:getoken()
elif token.token == jumpeq:
print("#==")
elif token.token == jumpne:
print("#!=")
elif token.token == lessthanequal:
print("#<=")
elif token.token == greaterthanequal:
print("#<=")
elif token.token == semicolon: getoken()
elif token.token == rightbrace: print("")
else: error("Start of Factor expected")
#===============================================================================
def program():
#===============================================================================
""" # PROGRAM - Start production of the grammar
# <program> <function> ::= { <id> ; <vars > <stmtlist> }
"""
if token.token == programsym:
# print "name",tokenNames[token.token]
getoken()
else: error("Program start with 'program' keyword")
if token.token == idsym: getoken()
else: error("Program error - Program name expected")
if token.token == semicolon: getoken()
else: error("Program error - Semicolon 1 expected")
if token.token == declaresym :
vars()
if token.token == varsym :
vars()
if token.token == functionsym:
functionStmt()
if token.token == leftbrace:
getoken()
if token.token == printsym:
print("#print")
getoken()
if token.token == leftbracket: #(
getoken()
else: error(" ( expected")
#=================================================
# Start Function
#=================================================
if token.token == addup:
functionStmt()
#=================================================
# End Function
#=================================================
stmtList()
#=================================================
def functionStmt():
#=================================================
# <function> ::= { <id>; <vars > <stmtlist> }
#<parameters>::= <var>, <var>
print("#Start of Function")
getoken(); #skip function - already been recognised
# function name called addup
#combine addup(a) into one token
if token.token == addup: #addup
getoken();
if token.token == leftbracket: #(
getoken()
else: error(" ( expected")
if token.token == number:
emit(0,"loadv", token.value)
emit(0, "store", 1)
emit(0, "call", 27)
getoken()
if token.token == rightbracket:
getoken()
else: error("Function error: rightbracket expected")
if token.token == rightbracket:
emit(27, "loadv", 1)
emit(28, "add", 1)
emit(29, "store", 1)
emit(30, "return", 0)
getoken()
else: error("Function error: rightbracket expected")
if token.token == semicolon:
emit(0, "writeInt", 0)
getoken()
else: error("Function error: semicolon expected")
if token.token == idsym:
if token.name == "n":
tokenNames[token.token]= "addup_n"
print "#token:-",tokenNames[token.token]
getoken()
if token.token == rightbracket:getoken()
else: error("Function error: ) expected")
if token.token == semicolon:getoken()
else: error("Function error: semicolon expected")
if token.token == leftbrace:getoken()
else: error("Function error: { expected")
if token.token == idsym:getoken()
else: error("Function error: idsym expected")
if token.token == assignsym:getoken()
else: error("Function error: assignsym expected")
if token.token == idsym:getoken()
else: error("Function error: idsym expected")
if token.token == plus:getoken()
else: error("Function error: plus expected")
if token.token == number:getoken()
else: error("Function error: number expected")
if token.token == semicolon:getoken()
else: error("Function error: semicolon expected")
if token.token == returnvalue:getoken()
else: error("Function error: return expected")
if token.token == idsym:getoken()
else: error("Function error: idsym expected")
if token.token == semicolon:getoken()
else: error("Function error: semicolon expected")
if token.token == leftbrace:getoken()
else: error("Function error: { expected")
print("#End of function define \n")
#===============================================================================
def addup_a():
#===============================================================================
"""
emit(27, "add", 1)
emit(28, "return", 0)
"""
if token.token == leftbracket: #(
getoken()
if token.token == idsym:
getoken()
if token.token == number:
emit(0, "loadv", token.value)
emit(0, "store", 1)
getoken()
elif token.token == comma:
getoken()
if token.token == idsym:
getoken()
if token.token == number:
emit(0, "loadv", token.value)
emit(0, "call", 27)
emit(0, "add", 1)
emit(0, "return", 0)
else:emit(0,"return", 0)
if token.token == rightbracket:
getoken()
"""
if token.token == idsym: #a
factor()
if token.token == rightbracket: #)
tokenNames[token.token]= "addup_a"
print "#token:-",tokenNames[token.token]
getoken()
if token.token == leftbrace:
getoken()
if token.token == idsym:
factor()
if token.token == assignsym:
getoken()
if token.token == number:
factor()
if token.token == semicolon:
getoken()
if token.token ==returnvalue:
getoken()
if token.token == idsym:
factor()
tokenNames[token.token]= "return_a"
print "#token:-",tokenNames[token.token]
getoken()
else: error("Return expected")
if token.token == semicolon:
getoken()
if token.token ==return_a:
emit(0,"return", addup_a)
getoken()
else: error("Return_a expected")
if token.token == semicolon:
getoken()
if token.token == rightbrace:
getoken()
"""
# Compiler main function
#======================================================================
def main():
#======================================================================
global line
global srcfile
global outfile
global charIndex
initSymTbl()
srcfile = open('1Parameter.txt', 'r')
line = srcfile.read() # readline
# for line in open('tiny.txt', 'r'):
# if not line.startswith("#"):
# debugScanner = False
charIndex = 0
debugScanner = False
if debugScanner: # Scanner Test Routine - Read a line and display the tokens
getoken()
while token.token is not None: # Skeleton for testing Scanner
printToken(token)
# outfile.write(token)
getoken()
sys.exit(1)
else:
getoken() # Parse Program according to the grammar
program() # Call start non-terminal handler
#===============================================================================
# Main Compiler starts here
#===============================================================================
print "#Microcompiler.py v0.2"
srcfile = open('1Parameter.txt', 'r')
lexer = shlex.shlex(srcfile)
for token in lexer:
print "#"+repr(token)
emit(0, "load", 0)
emit(100, "constant", "'A'")
emit(101, "constant", "'P'")
emit(102, "constant", "'P'")
emit(103, "constant", "'L'")
emit(104, "constant", "'E'")
main()
#getoken()
| [
[
8,
0,
0.0032,
0.0053,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
8,
0,
0.0144,
0.0128,
0,
0.66,
0.0179,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0224,
0.0011,
0,
0.66,
... | [
"'''\nCreated on Jun 23, 2014\n\n@author: Brian\n'''",
"\"\"\" Giovanni's MicroCompiler Demo\n\n<program> ::= { <id> ; <vars > <stmtlist> }\n<vars> ::= V { <id> ; } % DECLARATIONS\n\n<stmtlist> ::= <stmt> { ; <stmt> }\n<stmt> ::= P <id> | <id> ... |
'''
Created on Jun 23, 2014
@author: Brian
'''
""" Giovanni's MicroCompiler Demo
<program> ::= { <id> ; <vars > <stmtlist> }
<vars> ::= V { <id> ; } % DECLARATIONS
<stmtlist> ::= <stmt> { ; <stmt> }
<stmt> ::= P <id> | <id> = <expr>
<expr> ::= <factor> { (+ | -) <factor> } % No precedence
<factor> ::= (+|-) ID | Number
"""
import sys
import shlex
#===============================================================================
# # Lexical Analyser - the "Scanner" - Define the TokenTypes
#===============================================================================
tokenNames =\
[ "unknownToken","programsym", "idsym", "assignsym", "leftbrace", "rightbrace","comma",
"varsym","functionsym", "semicolon", "whilesym", "leftbracket", "rightbracket",
"printsym","printmsg", "ifsym", "elsesym","declaresym","forsym", "equals", "notequals", "lessthan", "greaterthan",
"readch", "readint", "writech", "writeint","addup","addup_1",
"number", "plus", "minus", "mpy", "div", "jumpne", "jumpeq","lessthanequal","greaterthanequal","ex","remainder","returnvalue","return_a", "endfile"]
# define the tokens as variables
unknownToken,programsym, idsym, assignsym, leftbrace, rightbrace, comma,\
varsym,functionsym, semicolon, whilesym, leftbracket, rightbracket,\
printsym,printmsg, ifsym, elsesym,declaresym, forsym, equals, notequals, lessthan, greaterthan,\
readch, readint, writech, writeint, addup,addup_1,\
number, plus, minus, mpy, div, jumpne, jumpeq, lessthanequal, greaterthanequal,ex,remainder,returnvalue,return_a, endfile = range(0, len(tokenNames))
#===============================================================================
class symbol:
#===============================================================================
name = None # String representation
token = None; # Corresponding token
address = 0; # For variables, their runtime address
value = None # on defined for numbers
def __init__(self, name, token, value = 0):
self.name = name
self.token = token
self.address = 0 # for identifiers, their address
self.value = value # for numbers, their value
symtbl = {}; # The Symbol Table, a dictionary of symbols indexed by name
#======================================================================
# GLOBALS for output of Lexical Analyser
# Set by each call to GeToken()
token = None; # A symbol
line = "\n" # the complex source file as a string
charIndex = 0 # the position in the source
linenumber= 0 # The current number
EOF = chr(0)
#======================================================================
# Run Time Code Generation Variables
varptr = 500 # Arbitrary base address of memory for variables
codeptr = 10 # Address to output next instruction (for code)
#===============================================================================
# Symbol Table Management Routines
#===============================================================================
#===============================================================================
def addToSymTbl (name, token):
#===============================================================================
symtbl[name] = symbol(name, token) # Add a new symbol to the dictionary
return symtbl[name]
#===============================================================================
def lookup (thisName):
#===============================================================================
"# Find a given identifier in the Symbol Table, Return the symtbl entry"
if symtbl.has_key(thisName): # thisName has been seen before
return symtbl[thisName] # return the symtbl entry
else: return None
#===============================================================================
def initSymTbl():
#===============================================================================
"# Initialise Symbol Table, and preload reserved words"
addToSymTbl('var', varsym) # VAR
addToSymTbl('function', functionsym) # function
addToSymTbl('program', programsym) # function
addToSymTbl('declare', declaresym)
addToSymTbl('while', whilesym) # WHILE
addToSymTbl('for', forsym) # WHILE
addToSymTbl('print', printsym) # PRINT
addToSymTbl('printmsg', printmsg)#PRINTMESSAGE
addToSymTbl('if', ifsym) # IF
addToSymTbl('else', elsesym) # ELSE
addToSymTbl('readint', readint) #READINT
addToSymTbl('writeint', writeint) #READINT
addToSymTbl('readch', readch) #READINT
addToSymTbl('writech', writech) #READINT
addToSymTbl('addup', addup)#ADDUP
addToSymTbl('addup(1)',addup_1)
# Now add symbols - NB only single character symbols are here
# multicharacter one like ">=" are still to do
addToSymTbl( '=', assignsym)
addToSymTbl( '#', notequals)
addToSymTbl( '<', lessthan) #jumplt
addToSymTbl( '>', greaterthan) #jumpgt
addToSymTbl( '{', leftbrace )
addToSymTbl( '}', rightbrace)
addToSymTbl( '(', leftbracket)
addToSymTbl( ')', rightbracket)
addToSymTbl( '+', plus )
addToSymTbl( '-', minus)
addToSymTbl( '*', mpy)
addToSymTbl( '/', div)
addToSymTbl( ';', semicolon)
addToSymTbl( '!', ex)
addToSymTbl( '%', remainder)
addToSymTbl( ',', comma)
addToSymTbl( EOF, endfile)
#multicharacter one like ">=" are still to do
addToSymTbl( '==', jumpeq)
addToSymTbl( '!=', jumpne)
addToSymTbl( '<=', lessthanequal) #jumplt
addToSymTbl( '>=', greaterthanequal) #jumpgt
addToSymTbl( 'return', returnvalue)
addToSymTbl( 'return a', return_a)
#===============================================================================
# Scanner Diagnostics
#===============================================================================
def printToken(tok):
#===============================================================================
" - display the specified token."
if tok.token == idsym:
print "Token = %10s, %-10s adr = %3d" %\
(tokenNames[tok.token], tok.name, tok.address)
elif tok.token == number:
print "Token = %10s %d" % (tokenNames[tok.token], tok.value)
else:
print "Token = %10s" % tokenNames[tok.token]
#==============================?=================================================
def dumpSymTbl():
#===============================================================================
""" Dump all the tokens in the symboltable """
print(" *** Symbol Table ***")
for name in symtbl.keys(): # keys is a list of the names (printable form of tokens)
tok = symtbl[name]
if tok.token == idsym:
printToken(tok)
#===============================================================================
def getch():
#===============================================================================
global line
global charIndex
global linenumber
while True:
if charIndex < len(line): # See if used up current line
ch = line[charIndex] # if not, get character
charIndex = charIndex+1 # & move pointer for next time
else:
#line = srcfile.readline()
if line == "": line = EOF
#print "--> ",
line = raw_input() +"\n" # read new line, adding \n so it's like f.readline()
charIndex = 0 # & reset character pointer
linenumber = linenumber + 1
continue
if ch == "\n":
ch = " " # A newline is a token separator
if ch == "?":
dumpSymTbl()
continue
if ch == "#":
print "#Comment Found"
srcfile.read()
print "#Read next line"
return ch
#===============================================================================
def ungetch():
#===============================================================================
""" Unget the next character peeked at when building variables, numbers
and when distinguishing between >= and > ...
"""
global charIndex;
charIndex = charIndex-1;
#===============================================================================
def getoken():
#===============================================================================
""" GETOKEN - Put next token into the global TOKEN """
global token
ch = getch() # skip whitespace
while ch in ["\t", " ", "\n", "#"]:
ch = getch()
# If ch is alphabetic then this is start of reserved word or an identifier
if ch.isalpha(): # Letter therefore it's either identifier or reserved word
name = ""
while ch.isalpha() or ch.isdigit() or ch == "_":
name = name + ch
ch = getch()
ungetch() # let terminator be used next time
token = lookup(name) # See if token's known
if token is None: # if not
token = addToSymTbl(name, idsym) # add as 'idsym'-IDENTIFIER
return # we've set token.token to either id or tokentype of reserved word
#---------------------------------------------------------------------
# If it's numeric return TOKEN=number & token.value = binary value
elif ch.isdigit():
# In the real version, build number and don't forget to end with ungetch()
token = symbol(ch, number, value = int(ch)) # simplistic SINGLE DIGIT Ascii to Binary
return
#---------------------------------------------------------------------
# Single character tokens
elif ch in [",", "{", "}", "(", ")", "+" , "-", "*", "/", ";","%", EOF]:
token = lookup(ch) # preloaded with appropriate token
# special characters
# check ==
elif ch in ["!"]:
ch = getch()
char = "!"
nEqual = "!="
if ch == "=":
char = nEqual
ch = getch()
else:
token = lookup(ch)
ungetch()
token = lookup(char)
if token is None:
token = addToSymTbl(char, idsym)
return
# check ==
elif ch in ["="]:
ch = getch()
char = "="
Equal = "=="
if ch == "=":
char = Equal
ch = getch()
else:
token = lookup(ch)
ungetch()
token = lookup(char)
if token is None:
token = addToSymTbl(char, idsym)
return
# check <=
elif ch in ["<"]:
ch = getch()
char = "<"
lessthanEqual = "<="
if ch == "=":
char = lessthanEqual
ch = getch()
else:
token = lookup(ch)
ungetch()
token = lookup(char)
if token is None:
token = addToSymTbl(char, idsym)
return
# check >=
elif ch in [">"]:
ch = getch()
char = ">"
greatthanEqual = ">="
if ch == "=":
char = greatthanEqual
ch = getch()
else:
token = lookup(ch)
ungetch()
token = lookup(char)
if token is None:
token = addToSymTbl(char, idsym)
return
elif ch in ["addup"]:
ch = getch()
addup_a = "addup(a)"
if ch == "(":
ch = getch()
if ch == "a":
ch = getch()
if ch == ")":
char = addup_a
else:
token = lookup(ch)
else:
token = lookup(ch)
else:
token = lookup(ch)
ungetch()
token = lookup(char)
if token is None:
token = addToSymTbl(char, idsym)
return
elif token.token ==return_a:
emit(0,"return", 0)
getoken()
else:
print "Unknown character -->%s<- decimal %d" % (ch,ord(ch))
sys.exit(1) # Abort Compilation
#======================================================================
# THE GRAMMAR
# <program> ::= { <id> ; <vars > <stmtlist> }
# <vars> ::= var { <id> ; } % DECLARATIONS
# <array> ::= [<expr>]
# <stmtlist> ::= <stmt> { ; <stmt> }
# <stmt> ::= print <id>
# <id> = <expr>
# <expr> ::= <factor> { (+ | -) <factor> } % No precedence
# <factor> ::= [+/-] ID | Number
#======================================================================
# Centralised Parser Error Message handler
#======================================================================
#===============================================================================
def error (msg):
#===============================================================================
print line
print "-" * charIndex,"^"
print("Error on %d - %s\n" % (number, msg))
printToken(token)
print("\n")
#===============================================================================
def emit (memadr, opcode, parameter):
#===============================================================================
"""EMIT CODE - Emit a of code with a Parameter
if first arg is zero - (the memory address), use and incr CODEPTR"""
global codeptr
if (memadr == 0):
memadr = codeptr
codeptr = codeptr+1
print "%6d %-8s %-7s" % (memadr, opcode, parameter)
#======================================================================
# VARIABLE DECLARATIONS
# <vars> ::= V { <id> ; }
#===============================================================================
def vars() :
#===============================================================================
global varptr;
getoken(); #skip VARSYM - already been recognised
while (token.token == idsym):
if token.address != 0:
print("%c already declared\n", token.name);
else:
symtbl[token.name].address = varptr;
varptr = varptr +1
getoken(); #skip past identifier
if token.token == semicolon: getoken() #skip ;
elif token.token == assignsym: getoken()
else: error("semicolon expected in declaration")
#===============================================================================
def parameters(value1):
#<parameters> ::= (<value>)
#===============================================================================
global va1;
if token.token == leftbracket:getoken();
#1st variable
if token.token == number:
emit(0, "loadv", token.value)
if token.token == rightbracket: getoken();
#======================================================================
# STMTLIST
# <stmtlist> ::= <stmt> { ; <stmt> }
#===============================================================================
def stmtList():
#===============================================================================
stmt()
while (token.token == semicolon):
getoken() #skip ;
stmt()
#======================================================================
# STMT
#===============================================================================
def stmt():
#===============================================================================
""" <stmt> ::= print <expression> | <id> = <expression> | if <expression> | while <expression>
"""
global codeptr
# thisStmtAdr = codeptr # Jump DEMO - not part of Stmt
if token.token == printsym:
printStmt()
elif token.token == printmsg:
printMsg()
elif token.token == addup:
addup()
elif token.token == idsym:
assignStmt()
elif token.token == assignsym:
getoken()
elif token.token == varsym:
vars()
elif token.token == ifsym:
ifStmt()
elif token.token == elsesym:
elseStmt()
elif token.token == whilesym:
whileStmt()
elif token.token == readint:
readIntStmt()
elif token.token == readch:
readChStmt()
elif token.token == writeint:
writeIntStmt()
elif token.token == writech:
writeChStmt()
elif token.token == functionsym:
functionStmt()
elif token.token == rightbrace:
print("")
elif token.token == semicolon:
print("")
else:
error("Expected start of a statement")
# emit (0, "return", thisStmtAdr) # Jump DEMO
#===============================================================================
def printStmt():
#===============================================================================
""" <printStmt> ::= print <expression>"""
getoken() # skip "print"
expression() # on return, expr result (at runtime) will be in ACC
emit(0, "writeint", 0) # Memory address 0 is the ACC
if token.token == rightbrace:
print("#\n*** Compilation finished ***\n")
#===============================================================================
def printMsg():
#===============================================================================
""" <printMsg> ::= printMsg <expression>"""
print("#Print String APPLE to memory")
emit(0, "loadv", 100)
emit(0, "store", 1)
emit(0, "call", 40)
emit(40, "load-Ind", 0)
emit(41, "jumpeq", 45)
emit(42, "writech",150)
emit(43, "increment", 1)
emit(44, "jump", 40)
emit(45, "return", 0)
#===============================================================================
def assignStmt():
#===============================================================================
"""
<id> = <expression>
"""
whichidentifier = token # Remember which ID on Left
getoken() # Get token after identifier
if token.token == notequals: # skip # then read next line
srcfile.read()
getoken()
elif token.token == assignsym: #if the next token is =
expression()
elif token.token == idsym: factor()
elif token.token == jumpeq: print("#")
elif token.token == jumpne: print("#")
elif token.token == lessthanequal: print("")
elif token.token == greaterthanequal: print("")
elif token.token == semicolon: getoken()
else:
error("Expected = in assignment statement")
expression()
# Save result into LHS runtime address
#===============================================================================
def ifStmt():
#if-then-else
#===============================================================================
""" <ifStmt> ::= if <expression>"""
getoken() # skip "if"
emit(0, "compare",60)
expression()
stmt()
emit(0, "return",0)
#===============================================================================
def elseStmt():
#if-then-else
#===============================================================================
""" <elseStmt> ::= else <expression>"""
getoken()
emit(0, "store", 888)
stmt()
#===============================================================================
def whileStmt():
#===============================================================================
""" <whileStmt> ::= while (condition)statement"""
getoken() # skip "if"
emit(0, "compare",50)
expression()
stmt()
emit(0, "increment", 1)
emit(0, "jumpi", 14)
#===============================================================================
def readIntStmt():
#===============================================================================
getoken()
expression() # skip "if"
emit(0, "readint",999)
#===============================================================================
def readChStmt():
#===============================================================================
getoken() # skip "if"
emit(0, "readch",11)
#===============================================================================
def writeIntStmt():
#===============================================================================
getoken() # skip "if"
expression()
emit(0, "writeint",50)
#===============================================================================
def writeChStmt():
#===============================================================================
getoken() # skip "if"
emit(0, "writech",51)
#===============================================================================
def expression():
#===============================================================================
"""
Leaves result in ACC at runtime
Use addresses 999 & 998 as Temporary variables
<expression> ::= <factor> { (+ | - | * | /) <factor> }
"""
factor()
while token.token == plus or token.token == minus:
op = token # remember +/-
getoken() # skip past +/-
emit(0, "store", 1) # Save current result
factor() # Evaluate next factor
#working
if op.token == plus: #+
emit(0, "call", 27)
elif op.token == minus: # - Subtract - have to swap operand order
emit(0, "store", 998)
emit(0, "load" , 999)
emit(0, "subtract", 998) # Leaves result in Acc
emit(0, "store", 880)
#===============================================================================
def factor():
#===============================================================================
"""
# FACTOR() - leaves result in ACC at runtime
<factor> ::= (+|-) identifier | number
"""
#Numbers
if token.token == idsym:
emit(0, "load", token.address)
getoken()
elif token.token == number:
emit(0, "loadv", token.value)
getoken()
elif token.token == assignsym:getoken()
elif token.token == jumpeq:
print("#==")
elif token.token == jumpne:
print("#!=")
elif token.token == lessthanequal:
print("#<=")
elif token.token == greaterthanequal:
print("#<=")
elif token.token == semicolon: getoken()
elif token.token == rightbrace: print("")
else: error("Start of Factor expected")
#===============================================================================
def program():
#===============================================================================
""" # PROGRAM - Start production of the grammar
# <program> <function> ::= { <id> ; <vars > <stmtlist> }
"""
if token.token == programsym:
# print "name",tokenNames[token.token]
getoken()
else: error("Program start with 'program' keyword")
if token.token == idsym: getoken()
else: error("Program error - Program name expected")
if token.token == semicolon: getoken()
else: error("Program error - Semicolon 1 expected")
if token.token == declaresym :
vars()
if token.token == varsym :
vars()
if token.token == functionsym:
functionStmt()
if token.token == leftbrace:
getoken()
if token.token == printsym:
print("#print")
getoken()
if token.token == leftbracket: #(
getoken()
else: error(" ( expected")
#=================================================
# Start Function
#=================================================
if token.token == addup:
functionStmt()
#=================================================
# End Function
#=================================================
stmtList()
#=================================================
def functionStmt():
#=================================================
# <function> ::= { <id>; <vars > <stmtlist> }
#<parameters>::= <var>, <var>
print("#Start of Function")
getoken(); #skip function - already been recognised
# function name called addup
#combine addup(a) into one token
if token.token == addup: #addup
getoken();
if token.token == leftbracket: #(
getoken()
else: error("Function error: ( expected")
if token.token == number:
emit(0, "loadv", token.value)
emit(0, "store", 1)
emit(0, "call", 27)
getoken()
if token.token == rightbracket:getoken()
else: error("Function error: rightbracket expected")
if token.token == rightbracket:
emit(27, "loadv", 1)
emit(28, "add", 1)
emit(29, "add", 200)
emit(30, "add", 201)
emit(31, "store", 1)
emit(32, "return", 0)
getoken()
else: error("Function error: rightbracket expected")
if token.token == semicolon:
emit(0, "writeInt", 0)
getoken()
else: error("Function error: semicolon expected")
if token.token == idsym:
if token.name == "n":
tokenNames[token.token]= "addup_n"
print "#token:-",tokenNames[token.token],"\n"
getoken()
if token.token == rightbracket:getoken()
else: error("Function error: ) expected")
if token.token == semicolon:getoken()
else: error("Function error: semicolon expected")
if token.token == leftbrace:getoken()
else: error("Function error: { expected")
#c=4;
#c aka local variable;
if token.token == idsym:getoken()
else: error("Function error: idsym expected")
if token.token == assignsym:getoken()
else: error("Function error: assignsym expected")
if token.token == number:
emit(0, "loadv", token.value)
emit(0, "store", 200)
getoken()
else: error("Function error: assignsym expected")
if token.token == semicolon:getoken()
else: error("Function error: semicolon expected")
#end of c=4;
#b=6;
#c aka local variable;
if token.token == idsym:getoken()
else: error("Function error: idsym expected")
if token.token == assignsym:getoken()
else: error("Function error: assignsym expected")
if token.token == number:
emit(0, "loadv", token.value)
emit(0, "store", 201)
getoken()
else: error("Function error: assignsym expected")
if token.token == semicolon:getoken()
else: error("Function error: semicolon expected")
#end of c=6;
# n=n+1;
if token.token == idsym:getoken()
else: error("Function error: idsym expected")
if token.token == assignsym:getoken()
else: error("Function error: assignsym expected")
if token.token == idsym:getoken()
else: error("Function error: idsym expected")
if token.token == plus:getoken()
else: error("Function error: plus expected")
if token.token == number:
# emit(0, "loadv", token.value)
getoken()
else: error("Function error: assignsym expected")
if token.token == semicolon:getoken()
else: error("Function error: semicolon expected")
#end of n=n+1;
#return n+c+b;
if token.token == returnvalue:getoken()
else: error("Function error: return expected")
if token.token == idsym:getoken()
else: error("Function error: idsym expected")
if token.token == plus:getoken()
else: error("Function error: plus expected")
if token.token == idsym:getoken()
else: error("Function error: idsym expected")
if token.token == plus:getoken()
else: error("Function error: plus expected")
if token.token == idsym:getoken()
else: error("Function error: idsym expected")
if token.token == semicolon:getoken()
else: error("Function error: semicolon expected")
#end return n+c;
#===============================================================================
def addup_a():
#===============================================================================
"""
emit(27, "add", 1)
emit(28, "return", 0)
"""
if token.token == leftbracket: #(
getoken()
if token.token == idsym:
getoken()
if token.token == number:
emit(0, "loadv", token.value)
emit(0, "store", 1)
getoken()
elif token.token == comma:
getoken()
if token.token == idsym:
getoken()
if token.token == number:
emit(0, "loadv", token.value)
emit(0, "call", 27)
emit(0, "add", 1)
emit(0, "return", 0)
else:emit(0,"return", 0)
if token.token == rightbracket:
getoken()
# Compiler main function
#======================================================================
def main():
#======================================================================
global line
global srcfile
global outfile
global charIndex
initSymTbl()
srcfile = open('function_local.txt', 'r')
line = srcfile.read() # readline
charIndex = 0
debugScanner = False
if debugScanner: # Scanner Test Routine - Read a line and display the tokens
getoken()
while token.token is not None: # Skeleton for testing Scanner
printToken(token)
# outfile.write(token)
getoken()
sys.exit(1)
else:
getoken() # Parse Program according to the grammar
program() # Call start non-terminal handler
#===============================================================================
# Main Compiler starts here
#===============================================================================
print "#Microcompiler.py v0.2"
srcfile = open('function_local.txt', 'r')
lexer = shlex.shlex(srcfile)
for token in lexer:
print "#"+repr(token)
emit(0, "load", 0)
emit(100, "constant", "'A'")
emit(101, "constant", "'P'")
emit(102, "constant", "'P'")
emit(103, "constant", "'L'")
emit(104, "constant", "'E'")
main()
#getoken()
| [
[
8,
0,
0.0032,
0.0054,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
8,
0,
0.0145,
0.0129,
0,
0.66,
0.0182,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0225,
0.0011,
0,
0.66,
... | [
"'''\nCreated on Jun 23, 2014\n\n@author: Brian\n'''",
"\"\"\" Giovanni's MicroCompiler Demo\n\n<program> ::= { <id> ; <vars > <stmtlist> }\n<vars> ::= V { <id> ; } % DECLARATIONS\n\n<stmtlist> ::= <stmt> { ; <stmt> }\n<stmt> ::= P <id> | <id> ... |
'''
Created on Jun 23, 2014
@author: Brian
'''
""" Giovanni's MicroCompiler Demo
<program> ::= { <id> ; <vars > <stmtlist> }
<vars> ::= V { <id> ; } % DECLARATIONS
<stmtlist> ::= <stmt> { ; <stmt> }
<stmt> ::= P <id> | <id> = <expr>
<expr> ::= <factor> { (+ | -) <factor> } % No precedence
<factor> ::= (+|-) ID | Number
"""
import sys
import shlex
#===============================================================================
# # Lexical Analyser - the "Scanner" - Define the TokenTypes
#===============================================================================
tokenNames =\
[ "unknownToken","programsym", "idsym", "assignsym", "leftbrace", "rightbrace","comma",
"varsym","functionsym", "semicolon", "whilesym", "leftbracket", "rightbracket",
"printsym","printmsg", "ifsym", "elsesym","declaresym","forsym", "equals", "notequals", "lessthan", "greaterthan",
"readch", "readint", "writech", "writeint","addup","addup_1",
"number", "plus", "minus", "mpy", "div", "jumpne", "jumpeq","lessthanequal","greaterthanequal","ex","remainder","returnvalue","return_a", "endfile"]
# define the tokens as variables
unknownToken,programsym, idsym, assignsym, leftbrace, rightbrace, comma,\
varsym,functionsym, semicolon, whilesym, leftbracket, rightbracket,\
printsym,printmsg, ifsym, elsesym,declaresym, forsym, equals, notequals, lessthan, greaterthan,\
readch, readint, writech, writeint, addup,addup_1,\
number, plus, minus, mpy, div, jumpne, jumpeq, lessthanequal, greaterthanequal,ex,remainder,returnvalue,return_a, endfile = range(0, len(tokenNames))
#===============================================================================
class symbol:
#===============================================================================
name = None # String representation
token = None; # Corresponding token
address = 0; # For variables, their runtime address
value = None # on defined for numbers
def __init__(self, name, token, value = 0):
self.name = name
self.token = token
self.address = 0 # for identifiers, their address
self.value = value # for numbers, their value
symtbl = {}; # The Symbol Table, a dictionary of symbols indexed by name
#======================================================================
# GLOBALS for output of Lexical Analyser
# Set by each call to GeToken()
token = None; # A symbol
line = "\n" # the complex source file as a string
charIndex = 0 # the position in the source
linenumber= 0 # The current number
EOF = chr(0)
#======================================================================
# Run Time Code Generation Variables
varptr = 500 # Arbitrary base address of memory for variables
codeptr = 10 # Address to output next instruction (for code)
#===============================================================================
# Symbol Table Management Routines
#===============================================================================
#===============================================================================
def addToSymTbl (name, token):
#===============================================================================
symtbl[name] = symbol(name, token) # Add a new symbol to the dictionary
return symtbl[name]
#===============================================================================
def lookup (thisName):
#===============================================================================
"# Find a given identifier in the Symbol Table, Return the symtbl entry"
if symtbl.has_key(thisName): # thisName has been seen before
return symtbl[thisName] # return the symtbl entry
else: return None
#===============================================================================
def initSymTbl():
#===============================================================================
"# Initialise Symbol Table, and preload reserved words"
addToSymTbl('var', varsym) # VAR
addToSymTbl('function', functionsym) # function
addToSymTbl('program', programsym) # function
addToSymTbl('declare', declaresym)
addToSymTbl('while', whilesym) # WHILE
addToSymTbl('for', forsym) # WHILE
addToSymTbl('print', printsym) # PRINT
addToSymTbl('printmsg', printmsg)#PRINTMESSAGE
addToSymTbl('if', ifsym) # IF
addToSymTbl('else', elsesym) # ELSE
addToSymTbl('readint', readint) #READINT
addToSymTbl('writeint', writeint) #READINT
addToSymTbl('readch', readch) #READINT
addToSymTbl('writech', writech) #READINT
addToSymTbl('addup', addup)#ADDUP
addToSymTbl('addup(1)',addup_1)
# Now add symbols - NB only single character symbols are here
# multicharacter one like ">=" are still to do
addToSymTbl( '=', assignsym)
addToSymTbl( '#', notequals)
addToSymTbl( '<', lessthan) #jumplt
addToSymTbl( '>', greaterthan) #jumpgt
addToSymTbl( '{', leftbrace )
addToSymTbl( '}', rightbrace)
addToSymTbl( '(', leftbracket)
addToSymTbl( ')', rightbracket)
addToSymTbl( '+', plus )
addToSymTbl( '-', minus)
addToSymTbl( '*', mpy)
addToSymTbl( '/', div)
addToSymTbl( ';', semicolon)
addToSymTbl( '!', ex)
addToSymTbl( '%', remainder)
addToSymTbl( ',', comma)
addToSymTbl( EOF, endfile)
#multicharacter one like ">=" are still to do
addToSymTbl( '==', jumpeq)
addToSymTbl( '!=', jumpne)
addToSymTbl( '<=', lessthanequal) #jumplt
addToSymTbl( '>=', greaterthanequal) #jumpgt
addToSymTbl( 'return', returnvalue)
addToSymTbl( 'return a', return_a)
#===============================================================================
# Scanner Diagnostics
#===============================================================================
def printToken(tok):
#===============================================================================
" - display the specified token."
if tok.token == idsym:
print "Token = %10s, %-10s adr = %3d" %\
(tokenNames[tok.token], tok.name, tok.address)
elif tok.token == number:
print "Token = %10s %d" % (tokenNames[tok.token], tok.value)
else:
print "Token = %10s" % tokenNames[tok.token]
#==============================?=================================================
def dumpSymTbl():
#===============================================================================
""" Dump all the tokens in the symboltable """
print(" *** Symbol Table ***")
for name in symtbl.keys(): # keys is a list of the names (printable form of tokens)
tok = symtbl[name]
if tok.token == idsym:
printToken(tok)
#===============================================================================
def getch():
#===============================================================================
global line
global charIndex
global linenumber
while True:
if charIndex < len(line): # See if used up current line
ch = line[charIndex] # if not, get character
charIndex = charIndex+1 # & move pointer for next time
else:
#line = srcfile.readline()
if line == "": line = EOF
#print "--> ",
line = raw_input() +"\n" # read new line, adding \n so it's like f.readline()
charIndex = 0 # & reset character pointer
linenumber = linenumber + 1
continue
if ch == "\n":
ch = " " # A newline is a token separator
if ch == "?":
dumpSymTbl()
continue
if ch == "#":
print "#Comment Found"
srcfile.read()
print "#Read next line"
return ch
#===============================================================================
def ungetch():
#===============================================================================
""" Unget the next character peeked at when building variables, numbers
and when distinguishing between >= and > ...
"""
global charIndex;
charIndex = charIndex-1;
#===============================================================================
def getoken():
#===============================================================================
""" GETOKEN - Put next token into the global TOKEN """
global token
ch = getch() # skip whitespace
while ch in ["\t", " ", "\n", "#"]:
ch = getch()
# If ch is alphabetic then this is start of reserved word or an identifier
if ch.isalpha(): # Letter therefore it's either identifier or reserved word
name = ""
while ch.isalpha() or ch.isdigit() or ch == "_":
name = name + ch
ch = getch()
ungetch() # let terminator be used next time
token = lookup(name) # See if token's known
if token is None: # if not
token = addToSymTbl(name, idsym) # add as 'idsym'-IDENTIFIER
return # we've set token.token to either id or tokentype of reserved word
#---------------------------------------------------------------------
# If it's numeric return TOKEN=number & token.value = binary value
elif ch.isdigit():
# In the real version, build number and don't forget to end with ungetch()
token = symbol(ch, number, value = int(ch)) # simplistic SINGLE DIGIT Ascii to Binary
return
#---------------------------------------------------------------------
# Single character tokens
elif ch in [",", "{", "}", "(", ")", "+" , "-", "*", "/", ";","%", EOF]:
token = lookup(ch) # preloaded with appropriate token
# special characters
# check ==
elif ch in ["!"]:
ch = getch()
char = "!"
nEqual = "!="
if ch == "=":
char = nEqual
ch = getch()
else:
token = lookup(ch)
ungetch()
token = lookup(char)
if token is None:
token = addToSymTbl(char, idsym)
return
# check ==
elif ch in ["="]:
ch = getch()
char = "="
Equal = "=="
if ch == "=":
char = Equal
ch = getch()
else:
token = lookup(ch)
ungetch()
token = lookup(char)
if token is None:
token = addToSymTbl(char, idsym)
return
# check <=
elif ch in ["<"]:
ch = getch()
char = "<"
lessthanEqual = "<="
if ch == "=":
char = lessthanEqual
ch = getch()
else:
token = lookup(ch)
ungetch()
token = lookup(char)
if token is None:
token = addToSymTbl(char, idsym)
return
# check >=
elif ch in [">"]:
ch = getch()
char = ">"
greatthanEqual = ">="
if ch == "=":
char = greatthanEqual
ch = getch()
else:
token = lookup(ch)
ungetch()
token = lookup(char)
if token is None:
token = addToSymTbl(char, idsym)
return
elif ch in ["addup"]:
ch = getch()
addup_a = "addup(a)"
if ch == "(":
ch = getch()
if ch == "a":
ch = getch()
if ch == ")":
char = addup_a
else:
token = lookup(ch)
else:
token = lookup(ch)
else:
token = lookup(ch)
ungetch()
token = lookup(char)
if token is None:
token = addToSymTbl(char, idsym)
return
elif token.token ==return_a:
emit(0,"return", 0)
getoken()
else:
print "Unknown character -->%s<- decimal %d" % (ch,ord(ch))
sys.exit(1) # Abort Compilation
#======================================================================
# THE GRAMMAR
# <program> ::= { <id> ; <vars > <stmtlist> }
# <vars> ::= var { <id> ; } % DECLARATIONS
# <array> ::= [<expr>]
# <stmtlist> ::= <stmt> { ; <stmt> }
# <stmt> ::= print <id>
# <id> = <expr>
# <expr> ::= <factor> { (+ | -) <factor> } % No precedence
# <factor> ::= [+/-] ID | Number
#======================================================================
# Centralised Parser Error Message handler
#======================================================================
#===============================================================================
def error (msg):
#===============================================================================
print line
print "-" * charIndex,"^"
print("Error on %d - %s\n" % (number, msg))
printToken(token)
print("\n")
#===============================================================================
def emit (memadr, opcode, parameter):
#===============================================================================
"""EMIT CODE - Emit a of code with a Parameter
if first arg is zero - (the memory address), use and incr CODEPTR"""
global codeptr
if (memadr == 0):
memadr = codeptr
codeptr = codeptr+1
print "%6d %-8s %-7s" % (memadr, opcode, parameter)
#======================================================================
# VARIABLE DECLARATIONS
# <vars> ::= V { <id> ; }
#===============================================================================
def vars() :
#===============================================================================
global varptr;
getoken(); #skip VARSYM - already been recognised
while (token.token == idsym):
if token.address != 0:
print("%c already declared\n", token.name);
else:
symtbl[token.name].address = varptr;
varptr = varptr +1
getoken(); #skip past identifier
if token.token == semicolon: getoken() #skip ;
elif token.token == assignsym: getoken()
else: error("semicolon expected in declaration")
#===============================================================================
def parameters(value1):
#<parameters> ::= (<value>)
#===============================================================================
global va1;
if token.token == leftbracket:getoken();
#1st variable
if token.token == number:
emit(0, "loadv", token.value)
if token.token == rightbracket: getoken();
#======================================================================
# STMTLIST
# <stmtlist> ::= <stmt> { ; <stmt> }
#===============================================================================
def stmtList():
#===============================================================================
stmt()
while (token.token == semicolon):
getoken() #skip ;
stmt()
#======================================================================
# STMT
#===============================================================================
def stmt():
#===============================================================================
""" <stmt> ::= print <expression> | <id> = <expression> | if <expression> | while <expression>
"""
global codeptr
# thisStmtAdr = codeptr # Jump DEMO - not part of Stmt
if token.token == printsym:
printStmt()
elif token.token == printmsg:
printMsg()
elif token.token == addup:
addup()
elif token.token == idsym:
assignStmt()
elif token.token == assignsym:
getoken()
elif token.token == varsym:
vars()
elif token.token == ifsym:
ifStmt()
elif token.token == elsesym:
elseStmt()
elif token.token == whilesym:
whileStmt()
elif token.token == readint:
readIntStmt()
elif token.token == readch:
readChStmt()
elif token.token == writeint:
writeIntStmt()
elif token.token == writech:
writeChStmt()
elif token.token == functionsym:
functionStmt()
elif token.token == rightbrace:
print("")
elif token.token == semicolon:
print("")
else:
error("Expected start of a statement")
# emit (0, "return", thisStmtAdr) # Jump DEMO
#===============================================================================
def printStmt():
#===============================================================================
""" <printStmt> ::= print <expression>"""
getoken() # skip "print"
expression() # on return, expr result (at runtime) will be in ACC
emit(0, "writeint", 0) # Memory address 0 is the ACC
if token.token == rightbrace:
print("#\n*** Compilation finished ***\n")
#===============================================================================
def printMsg():
#===============================================================================
""" <printMsg> ::= printMsg <expression>"""
print("#Print String APPLE to memory")
emit(0, "loadv", 100)
emit(0, "store", 1)
emit(0, "call", 40)
emit(40, "load-Ind", 0)
emit(41, "jumpeq", 45)
emit(42, "writech",150)
emit(43, "increment", 1)
emit(44, "jump", 40)
emit(45, "return", 0)
#===============================================================================
def assignStmt():
#===============================================================================
"""
<id> = <expression>
"""
whichidentifier = token # Remember which ID on Left
getoken() # Get token after identifier
if token.token == notequals: # skip # then read next line
srcfile.read()
getoken()
elif token.token == assignsym: #if the next token is =
expression()
elif token.token == idsym: factor()
elif token.token == jumpeq: print("#")
elif token.token == jumpne: print("#")
elif token.token == lessthanequal: print("")
elif token.token == greaterthanequal: print("")
elif token.token == semicolon: getoken()
else:
error("Expected = in assignment statement")
expression()
# Save result into LHS runtime address
#===============================================================================
def ifStmt():
#if-then-else
#===============================================================================
""" <ifStmt> ::= if <expression>"""
getoken() # skip "if"
emit(0, "compare",60)
expression()
stmt()
emit(0, "return",0)
#===============================================================================
def elseStmt():
#if-then-else
#===============================================================================
""" <elseStmt> ::= else <expression>"""
getoken()
emit(0, "store", 888)
stmt()
#===============================================================================
def whileStmt():
#===============================================================================
""" <whileStmt> ::= while (condition)statement"""
getoken() # skip "if"
emit(0, "compare",50)
expression()
stmt()
emit(0, "increment", 1)
emit(0, "jumpi", 14)
#===============================================================================
def readIntStmt():
#===============================================================================
getoken()
expression() # skip "if"
emit(0, "readint",999)
#===============================================================================
def readChStmt():
#===============================================================================
getoken() # skip "if"
emit(0, "readch",11)
#===============================================================================
def writeIntStmt():
#===============================================================================
getoken() # skip "if"
expression()
emit(0, "writeint",50)
#===============================================================================
def writeChStmt():
#===============================================================================
getoken() # skip "if"
emit(0, "writech",51)
#===============================================================================
def expression():
#===============================================================================
"""
Leaves result in ACC at runtime
Use addresses 999 & 998 as Temporary variables
<expression> ::= <factor> { (+ | - | * | /) <factor> }
"""
factor()
while token.token == plus or token.token == minus:
op = token # remember +/-
getoken() # skip past +/-
emit(0, "store", 1) # Save current result
factor() # Evaluate next factor
#working
if op.token == plus: #+
emit(0, "call", 27)
elif op.token == minus: # - Subtract - have to swap operand order
emit(0, "store", 998)
emit(0, "load" , 999)
emit(0, "subtract", 998) # Leaves result in Acc
emit(0, "store", 880)
#===============================================================================
def factor():
#===============================================================================
"""
# FACTOR() - leaves result in ACC at runtime
<factor> ::= (+|-) identifier | number
"""
#Numbers
if token.token == idsym:
emit(0, "load", token.address)
getoken()
elif token.token == number:
emit(0, "loadv", token.value)
getoken()
elif token.token == assignsym:getoken()
elif token.token == jumpeq:
print("#==")
elif token.token == jumpne:
print("#!=")
elif token.token == lessthanequal:
print("#<=")
elif token.token == greaterthanequal:
print("#<=")
elif token.token == semicolon: getoken()
elif token.token == rightbrace: print("")
else: error("Start of Factor expected")
#===============================================================================
def program():
#===============================================================================
""" # PROGRAM - Start production of the grammar
# <program> <function> ::= { <id> ; <vars > <stmtlist> }
"""
if token.token == programsym:
# print "name",tokenNames[token.token]
getoken()
else: error("Program start with 'program' keyword")
if token.token == idsym: getoken()
else: error("Program error - Program name expected")
if token.token == semicolon: getoken()
else: error("Program error - Semicolon 1 expected")
if token.token == declaresym :
vars()
if token.token == varsym :
vars()
if token.token == functionsym:
functionStmt()
if token.token == leftbrace:
getoken()
if token.token == printsym:
print("#print")
getoken()
if token.token == leftbracket: #(
getoken()
else: error(" ( expected")
#=================================================
# Start Function
#=================================================
if token.token == addup:
functionStmt()
#=================================================
# End Function
#=================================================
stmtList()
#=================================================
def functionStmt():
#=================================================
# <function> ::= { <id>; <vars > <stmtlist> }
#<parameters>::= <var>, <var>
print("#Start of Function")
getoken(); #skip function - already been recognised
# function name called addup
#combine addup(a) into one token
if token.token == addup: #addup
getoken();
if token.token == leftbracket: #(
getoken()
else: error(" ( expected")
if token.token == number:
emit(0,"loadv", token.value)
emit(0, "store", 1)
getoken()
if token.token == comma:
getoken()
if token.token == number:
emit(0, "loadv", token.value)
getoken()
if token.token == rightbracket:
getoken()
if token.token == rightbracket:
emit(0, "call", 28)
emit(28, "add", 1)
emit(29, "store", 1)
emit(30, "return", 0)
getoken()
if token.token == semicolon:
emit(0, "writeInt", 0)
getoken()
if token.token == idsym:
if token.name == "n":
tokenNames[token.token]= "addup_n"
print "#token:-",tokenNames[token.token]
getoken()
if token.token == comma: getoken()
if token.name == "m":
tokenNames[token.token]= "addup_m"
print "#token:-",tokenNames[token.token]
getoken()
if token.token == rightbracket:getoken()
else: error("Function error: ) expected")
if token.token == semicolon:getoken()
else: error("Function error: semicolon expected")
if token.token == leftbrace:getoken()
else: error("Function error: { expected")
if token.token == idsym:getoken()
else: error("Function error: idsym expected")
if token.token == assignsym:getoken()
else: error("Function error: assignsym expected")
if token.token == idsym:getoken()
else: error("Function error: idsym expected")
if token.token == plus:getoken()
else: error("Function error: plus expected")
if token.token == idsym:getoken()
else: error("Function error: idsym expected")
if token.token == semicolon:getoken()
else: error("Function error: semicolon expected")
if token.token == returnvalue:getoken()
else: error("Function error: return expected")
if token.token == idsym:getoken()
else: error("Function error: idsym expected")
if token.token == semicolon:getoken()
else: error("Function error: semicolon expected")
if token.token == leftbrace:getoken()
else: error("Function error: { expected")
print("#End of function define \n")
#===============================================================================
def addup_a():
#===============================================================================
"""
emit(27, "add", 1)
emit(28, "return", 0)
"""
if token.token == leftbracket: #(
getoken()
if token.token == idsym:
getoken()
if token.token == number:
emit(0, "loadv", token.value)
emit(0, "store", 1)
getoken()
elif token.token == comma:
getoken()
if token.token == idsym:
getoken()
if token.token == number:
emit(0, "loadv", token.value)
emit(0, "call", 27)
emit(0, "add", 1)
emit(0, "return", 0)
else:emit(0,"return", 0)
if token.token == rightbracket:
getoken()
# Compiler main function
#======================================================================
def main():
#======================================================================
global line
global srcfile
global outfile
global charIndex
initSymTbl()
srcfile = open('parameter_more.txt', 'r')
line = srcfile.read() # readline
# for line in open('tiny.txt', 'r'):
# if not line.startswith("#"):
# debugScanner = False
charIndex = 0
debugScanner = False
if debugScanner: # Scanner Test Routine - Read a line and display the tokens
getoken()
while token.token is not None: # Skeleton for testing Scanner
printToken(token)
# outfile.write(token)
getoken()
sys.exit(1)
else:
getoken() # Parse Program according to the grammar
program() # Call start non-terminal handler
#===============================================================================
# Main Compiler starts here
#===============================================================================
print "#Microcompiler.py v0.2"
srcfile = open('parameter_more.txt', 'r')
lexer = shlex.shlex(srcfile)
for token in lexer:
print "#"+repr(token)
emit(0, "load", 0)
emit(100, "constant", "'A'")
emit(101, "constant", "'P'")
emit(102, "constant", "'P'")
emit(103, "constant", "'L'")
emit(104, "constant", "'E'")
main()
#getoken()
| [
[
8,
0,
0.0033,
0.0056,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
8,
0,
0.0151,
0.0134,
0,
0.66,
0.0182,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0234,
0.0011,
0,
0.66,
... | [
"'''\nCreated on Jun 23, 2014\n\n@author: Brian\n'''",
"\"\"\" Giovanni's MicroCompiler Demo\n\n<program> ::= { <id> ; <vars > <stmtlist> }\n<vars> ::= V { <id> ; } % DECLARATIONS\n\n<stmtlist> ::= <stmt> { ; <stmt> }\n<stmt> ::= P <id> | <id> ... |
'''
Created on Jun 23, 2014
@author: Brian
'''
""" Giovanni's MicroCompiler Demo
<program> ::= { <id> ; <vars > <stmtlist> }
<vars> ::= V { <id> ; } % DECLARATIONS
<stmtlist> ::= <stmt> { ; <stmt> }
<stmt> ::= P <id> | <id> = <expr>
<expr> ::= <factor> { (+ | -) <factor> } % No precedence
<factor> ::= (+|-) ID | Number
"""
import sys
import shlex
import math
#===============================================================================
# # Lexical Analyser - the "Scanner" - Define the TokenTypes
#===============================================================================
tokenNames =\
[ "unknownToken","programsym", "idsym", "assignsym", "leftbrace", "rightbrace","comma",
"varsym","functionsym", "semicolon", "whilesym", "leftbracket", "rightbracket","quote",
"printsym","printmsg", "ifsym", "elsesym","declaresym","forsym", "equals", "notequals", "lessthan", "greaterthan",
"readch", "readint", "writech", "writeint","addup","addup_1","fact","stringsym",
"number", "plus", "minus", "mpy", "div", "jumpne", "jumpeq","lessthanequal","greaterthanequal","ex","remainder","returnvalue","return_a", "endfile"]
# define the tokens as variables
unknownToken,programsym, idsym, assignsym, leftbrace, rightbrace, comma,\
varsym,functionsym, semicolon, whilesym, leftbracket, rightbracket,quote,\
printsym,printmsg, ifsym, elsesym,declaresym, forsym, equals, notequals, lessthan, greaterthan,\
readch, readint, writech, writeint, addup,addup_1,fact,stringsym,\
number, plus, minus, mpy, div, jumpne, jumpeq, lessthanequal, greaterthanequal,ex,remainder,returnvalue,return_a, endfile = range(0, len(tokenNames))
#===============================================================================
class symbol:
#===============================================================================
name = None # String representation
token = None; # Corresponding token
address = 0; # For variables, their runtime address
value = None # on defined for numbers
def __init__(self, name, token, value = 0):
self.name = name
self.token = token
self.address = 0 # for identifiers, their address
self.value = value # for numbers, their value
symtbl = {}; # The Symbol Table, a dictionary of symbols indexed by name
#======================================================================
# GLOBALS for output of Lexical Analyser
# Set by each call to GeToken()
token = None; # A symbol
line = "\n" # the complex source file as a string
charIndex = 0 # the position in the source
linenumber= 0 # The current number
EOF = chr(0)
#======================================================================
# Run Time Code Generation Variables
varptr = 500 # Arbitrary base address of memory for variables
codeptr = 10 # Address to output next instruction (for code)
#===============================================================================
# Symbol Table Management Routines
#===============================================================================
#===============================================================================
def addToSymTbl (name, token):
#===============================================================================
symtbl[name] = symbol(name, token) # Add a new symbol to the dictionary
return symtbl[name]
#===============================================================================
def lookup (thisName):
#===============================================================================
"# Find a given identifier in the Symbol Table, Return the symtbl entry"
if symtbl.has_key(thisName): # thisName has been seen before
return symtbl[thisName] # return the symtbl entry
else: return None
#===============================================================================
def initSymTbl():
#===============================================================================
"# Initialise Symbol Table, and preload reserved words"
addToSymTbl('var', varsym) # VAR
addToSymTbl('function', functionsym) # function
addToSymTbl('program', programsym) # function
addToSymTbl('declare', declaresym)
addToSymTbl('while', whilesym) # WHILE
addToSymTbl('for', forsym) # WHILE
addToSymTbl('print', printsym) # PRINT
addToSymTbl('printmsg', printmsg)#PRINTMESSAGE
addToSymTbl('if', ifsym) # IF
addToSymTbl('else', elsesym) # ELSE
addToSymTbl('readint', readint) #READINT
addToSymTbl('writeint', writeint) #READINT
addToSymTbl('readch', readch) #READINT
addToSymTbl('writech', writech) #READINT
addToSymTbl('addup', addup)#ADDUP
addToSymTbl('addup(1)',addup_1)
addToSymTbl('fact', fact)
# Now add symbols - NB only single character symbols are here
# multicharacter one like ">=" are still to do
addToSymTbl( '=', assignsym)
addToSymTbl( '#', notequals)
addToSymTbl( '<', lessthan) #jumplt
addToSymTbl( '>', greaterthan) #jumpgt
addToSymTbl( '{', leftbrace )
addToSymTbl( '}', rightbrace)
addToSymTbl( '(', leftbracket)
addToSymTbl( ')', rightbracket)
addToSymTbl( '+', plus )
addToSymTbl( '-', minus)
addToSymTbl( '*', mpy)
addToSymTbl( '/', div)
addToSymTbl( ';', semicolon)
addToSymTbl( '!', ex)
addToSymTbl( '%', remainder)
addToSymTbl( ',', comma)
addToSymTbl("Factorial of 5 is", stringsym)
addToSymTbl( EOF, endfile)
#multicharacter one like ">=" are still to do
addToSymTbl( '==', jumpeq)
addToSymTbl( '!=', jumpne)
addToSymTbl( '<=', lessthanequal) #jumplt
addToSymTbl( '>=', greaterthanequal) #jumpgt
addToSymTbl( 'return', returnvalue)
addToSymTbl( 'return a', return_a)
addToSymTbl( '"',quote)
#===============================================================================
# Scanner Diagnostics
#===============================================================================
def printToken(tok):
#===============================================================================
" - display the specified token."
if tok.token == idsym:
print "Token = %10s, %-10s adr = %3d" %\
(tokenNames[tok.token], tok.name, tok.address)
elif tok.token == number:
print "Token = %10s %d" % (tokenNames[tok.token], tok.value)
else:
print "Token = %10s" % tokenNames[tok.token]
#==============================?=================================================
def dumpSymTbl():
#===============================================================================
""" Dump all the tokens in the symboltable """
print(" *** Symbol Table ***")
for name in symtbl.keys(): # keys is a list of the names (printable form of tokens)
tok = symtbl[name]
if tok.token == idsym:
printToken(tok)
#===============================================================================
def getch():
#===============================================================================
global line
global charIndex
global linenumber
while True:
if charIndex < len(line): # See if used up current line
ch = line[charIndex] # if not, get character
charIndex = charIndex+1 # & move pointer for next time
else:
#line = srcfile.readline()
if line == "": line = EOF
#print "--> ",
line = raw_input() +"\n" # read new line, adding \n so it's like f.readline()
charIndex = 0 # & reset character pointer
linenumber = linenumber + 1
continue
if ch == "\n":
ch = " " # A newline is a token separator
if ch == "?":
dumpSymTbl()
continue
if ch == "#":
print "#Comment Found"
srcfile.read()
print "#Read next line"
return ch
#===============================================================================
def ungetch():
#===============================================================================
""" Unget the next character peeked at when building variables, numbers
and when distinguishing between >= and > ...
"""
global charIndex;
charIndex = charIndex-1;
#===============================================================================
def getoken():
#===============================================================================
""" GETOKEN - Put next token into the global TOKEN """
global token
ch = getch() # skip whitespace
while ch in ["\t", " ", "\n", "#"]:
ch = getch()
# If ch is alphabetic then this is start of reserved word or an identifier
if ch.isalpha(): # Letter therefore it's either identifier or reserved word
name = ""
while ch.isalpha() or ch.isdigit() or ch == "_":
name = name + ch
ch = getch()
ungetch() # let terminator be used next time
token = lookup(name) # See if token's known
if token is None: # if not
token = addToSymTbl(name, idsym) # add as 'idsym'-IDENTIFIER
return # we've set token.token to either id or tokentype of reserved word
#---------------------------------------------------------------------
# If it's numeric return TOKEN=number & token.value = binary value
elif ch.isdigit():
# In the real version, build number and don't forget to end with ungetch()
token = symbol(ch, number, value = int(ch)) # simplistic SINGLE DIGIT Ascii to Binary
return
#---------------------------------------------------------------------
# Single character tokens
elif ch in [",", "{", "}", "(", ")", "+" , "-", "*", "/", ";","%",'"', EOF]:
token = lookup(ch) # preloaded with appropriate token
# special characters
# check ==
elif ch in ["!"]:
ch = getch()
char = "!"
nEqual = "!="
if ch == "=":
char = nEqual
ch = getch()
else:
token = lookup(ch)
ungetch()
token = lookup(char)
if token is None:
token = addToSymTbl(char, idsym)
return
# check ==
elif ch in ["="]:
ch = getch()
char = "="
Equal = "=="
if ch == "=":
char = Equal
ch = getch()
else:
token = lookup(ch)
ungetch()
token = lookup(char)
if token is None:
token = addToSymTbl(char, idsym)
return
# check <=
elif ch in ["<"]:
ch = getch()
char = "<"
lessthanEqual = "<="
if ch == "=":
char = lessthanEqual
ch = getch()
else:
token = lookup(ch)
ungetch()
token = lookup(char)
if token is None:
token = addToSymTbl(char, idsym)
return
# check >=
elif ch in [">"]:
ch = getch()
char = ">"
greatthanEqual = ">="
if ch == "=":
char = greatthanEqual
ch = getch()
else:
token = lookup(ch)
ungetch()
token = lookup(char)
if token is None:
token = addToSymTbl(char, idsym)
return
elif token.token ==return_a:
emit(0,"return", 0)
getoken()
else:
print "#Unknown character -->%s<- decimal %d" % (ch,ord(ch))
sys.exit(1) # Abort Compilation
#======================================================================
# THE GRAMMAR
# <program> ::= { <id> ; <vars > <stmtlist> }
# <vars> ::= var { <id> ; } % DECLARATIONS
# <array> ::= [<expr>]
# <stmtlist> ::= <stmt> { ; <stmt> }
# <stmt> ::= print <id>
# <id> = <expr>
# <expr> ::= <factor> { (+ | -) <factor> } % No precedence
# <factor> ::= [+/-] ID | Number
#======================================================================
# Centralised Parser Error Message handler
#======================================================================
#===============================================================================
def error (msg):
#===============================================================================
print line
print "-" * charIndex,"^"
print("Error on %d - %s\n" % (number, msg))
printToken(token)
print("\n")
#===============================================================================
def emit (memadr, opcode, parameter):
#===============================================================================
"""EMIT CODE - Emit a of code with a Parameter
if first arg is zero - (the memory address), use and incr CODEPTR"""
global codeptr
if (memadr == 0):
memadr = codeptr
codeptr = codeptr+1
print "%6d %-8s %-7s" % (memadr, opcode, parameter)
#======================================================================
# VARIABLE DECLARATIONS
# <vars> ::= V { <id> ; }
#===============================================================================
def vars() :
#===============================================================================
global varptr;
getoken(); #skip VARSYM - already been recognised
while (token.token == idsym):
if token.address != 0:
print("%c already declared\n", token.name);
else:
symtbl[token.name].address = varptr;
varptr = varptr +1
getoken(); #skip past identifier
if token.token == semicolon: getoken() #skip ;
elif token.token == assignsym: getoken()
else: error("semicolon expected in declaration")
#===============================================================================
def parameters(value1):
#<parameters> ::= (<value>)
#===============================================================================
global va1;
if token.token == leftbracket:getoken();
#1st variable
if token.token == number:
emit(0, "loadv", token.value)
if token.token == rightbracket: getoken();
#======================================================================
# STMTLIST
# <stmtlist> ::= <stmt> { ; <stmt> }
#===============================================================================
def stmtList():
#===============================================================================
stmt()
while (token.token == semicolon):
getoken() #skip ;
stmt()
#======================================================================
# STMT
#===============================================================================
def stmt():
#===============================================================================
""" <stmt> ::= print <expression> | <id> = <expression> | if <expression> | while <expression>
"""
global codeptr
# thisStmtAdr = codeptr # Jump DEMO - not part of Stmt
if token.token == printsym:
printStmt()
elif token.token == printmsg:
printMsg()
elif token.token == addup:
addup()
elif token.token == idsym:
assignStmt()
elif token.token == assignsym:
getoken()
elif token.token == varsym:
vars()
elif token.token == ifsym:
ifStmt()
elif token.token == elsesym:
elseStmt()
elif token.token == whilesym:
whileStmt()
elif token.token == readint:
readIntStmt()
elif token.token == readch:
readChStmt()
elif token.token == writeint:
writeIntStmt()
elif token.token == writech:
writeChStmt()
elif token.token == functionsym:
functionStmt()
elif token.token == rightbrace:
print("")
elif token.token == semicolon:
print("")
else:
error("Expected start of a statement")
# emit (0, "return", thisStmtAdr) # Jump DEMO
#===============================================================================
def printStmt():
#===============================================================================
""" <printStmt> ::= print <expression>"""
getoken() # skip "print"
expression() # on return, expr result (at runtime) will be in ACC
emit(0, "writeint", 0) # Memory address 0 is the ACC
if token.token == rightbrace:
print("#\n*** Compilation finished ***\n")
#===============================================================================
def printMsg():
#===============================================================================
""" <printMsg> ::= printMsg <expression>"""
print("#Print String APPLE to memory")
emit(0, "loadv", 100)
emit(0, "store", 1)
emit(0, "call", 40)
emit(40, "load-Ind", 0)
emit(41, "jumpeq", 45)
emit(42, "writech",150)
emit(43, "increment", 1)
emit(44, "jump", 40)
emit(45, "return", 0)
#===============================================================================
def assignStmt():
#===============================================================================
"""
<id> = <expression>
"""
whichidentifier = token # Remember which ID on Left
getoken() # Get token after identifier
if token.token == notequals: # skip # then read next line
srcfile.read()
getoken()
elif token.token == assignsym: #if the next token is =
expression()
elif token.token == idsym: factor()
elif token.token == jumpeq: print("#")
elif token.token == jumpne: print("#")
elif token.token == lessthanequal: print("")
elif token.token == greaterthanequal: print("")
elif token.token == semicolon: getoken()
else:
error("Expected = in assignment statement")
expression()
# Save result into LHS runtime address
#===============================================================================
def ifStmt():
#if-then-else
#===============================================================================
""" <ifStmt> ::= if <expression>"""
getoken() # skip "if"
emit(0, "compare",60)
expression()
stmt()
emit(0, "return",0)
#===============================================================================
def elseStmt():
#if-then-else
#===============================================================================
""" <elseStmt> ::= else <expression>"""
getoken()
emit(0, "store", 888)
stmt()
#===============================================================================
def whileStmt():
#===============================================================================
""" <whileStmt> ::= while (condition)statement"""
getoken() # skip "if"
emit(0, "compare",50)
expression()
stmt()
emit(0, "increment", 1)
emit(0, "jumpi", 14)
#===============================================================================
def readIntStmt():
#===============================================================================
getoken()
expression() # skip "if"
emit(0, "readint",999)
#===============================================================================
def readChStmt():
#===============================================================================
getoken() # skip "if"
emit(0, "readch",11)
#===============================================================================
def writeIntStmt():
#===============================================================================
getoken() # skip "if"
expression()
emit(0, "writeint",50)
#===============================================================================
def writeChStmt():
#===============================================================================
getoken() # skip "if"
emit(0, "writech",51)
#===============================================================================
def expression():
#===============================================================================
"""
Leaves result in ACC at runtime
Use addresses 999 & 998 as Temporary variables
<expression> ::= <factor> { (+ | - | * | /) <factor> }
"""
factor()
while token.token == plus or token.token == minus:
op = token # remember +/-
getoken() # skip past +/-
emit(0, "store", 1) # Save current result
factor() # Evaluate next factor
#working
if op.token == plus: #+
emit(0, "call", 27)
elif op.token == minus: # - Subtract - have to swap operand order
emit(0, "store", 998)
emit(0, "load" , 999)
emit(0, "subtract", 998) # Leaves result in Acc
emit(0, "store", 880)
#===============================================================================
def factor():
#===============================================================================
"""
# FACTOR() - leaves result in ACC at runtime
<factor> ::= (+|-) identifier | number
"""
#Numbers
if token.token == idsym:
emit(0, "load", token.address)
getoken()
elif token.token == number:
emit(0, "loadv", token.value)
getoken()
elif token.token == assignsym:getoken()
elif token.token == jumpeq:
print("#==")
elif token.token == jumpne:
print("#!=")
elif token.token == lessthanequal:
print("#<=")
elif token.token == greaterthanequal:
print("#<=")
elif token.token == semicolon: getoken()
elif token.token == rightbrace: print("")
else: error("Start of Factor expected")
#===============================================================================
def program():
#===============================================================================
""" # PROGRAM - Start production of the grammar
# <program> <function> ::= { <id> ; <vars > <stmtlist> }
"""
if token.token == programsym:
# print "name",tokenNames[token.token]
getoken()
else: error("Program start with 'program' keyword")
if token.token == idsym: getoken()
else: error("Program error - Program name expected")
if token.token == semicolon: getoken()
else: error("Program error - Semicolon 1 expected")
if token.token == declaresym :
vars()
getoken()
if token.token == varsym :
print("Decare "+token.name)
vars()
getoken()
if token.token == functionsym:
getoken()
if token.token == fact:
functionStmt()
getoken()
#print ("Factorial of 5 is ", factor(5));
if token.token == printsym:
print("#print factorial"+"\n")
getoken()
else: error("program error - print expected")
if token.token == leftbracket:
getoken()
else: error("program error - ( expected")
if token.token == quote:getoken()
else: error("program error - ' expected")
if token.token == idsym:
print("#"+token.name+""),
getoken()
else: error("program error - stringsym expected")
if token.token == idsym:
print(token.name+""),
getoken()
else: error("program error - stringsym expected")
if token.token == number:
print(str(token.value)+""),
getoken()
else: error("program error - stringsym expected")
if token.token == idsym:
print(token.name+"")
getoken()
else: error("program error - stringsym expected")
if token.token == quote:getoken()
else: error("program error - ' expected")
if token.token == comma:getoken()
if token.token == fact: functionStmt()
#}
if token.token == rightbrace:
getoken()
else:error("program error - } expected")
#=================================================
def functionStmt():
#=================================================
# <function> ::= { <id>; <vars > <stmtlist> }
#<parameters>::= <var>, <var>
#
getoken(); #skip function - already been recognised
# function name called addup
#combine addup(a) into one token
if token.token == fact: #addup
getoken();
if token.token == leftbracket: #(
getoken()
else: error("Function error: ( expected")
if token.token == number:
if token.value == 1:
emit(0, "loadv", 1)
emit(0, "store", 1)
emit(0, "writeInt", 0)
getoken()
else:
emit(0, "loadv", token.value)
emit(0, "store", 300)
emit(0, "call", 27)
getoken()
if token.token == rightbracket:
emit(28, "subtract", 105) #4
emit(29, "store",301)
emit(30, "subtract", 105) #3
emit(31, "store", 302)
emit(32, "subtract", 105) #2
emit(33, "store", 303)
emit(34, "subtract", 105) #1
emit(35, "mpy", 300)
emit(36, "mpy", 301)
emit(37, "mpy", 302)
emit(38, "mpy", 303)
emit(39, "store", 1)
getoken()
# else: error("Function error: rightbracket expected")
if token.token == rightbracket:
getoken()
# else: error("Function error: rightbracket expected")
if token.token == semicolon:
emit(0, "writeInt", 0)
print("#The Factorial of 5 is" +" "+ str(math.factorial(5)))
print("\n#*** Compilation finished ***\n")
getoken()
# else: error("Function error: semicolon expected")
if token.token == idsym:
print("#Start of Function")
if token.name == "n":
tokenNames[token.token]= "fact_n"
print "#token:-",tokenNames[token.token],"\n"
getoken()
if token.token == rightbracket:getoken()
else: error("Function error: ) expected")
if token.token == semicolon:getoken()
else: error("Function error: semicolon expected")
if token.token == leftbrace:getoken()
else: error("Function error: { expected")
#if (n==1) return(1);
if token.token == ifsym:getoken()
else: error("Function error: idsym expected")
if token.token == leftbracket:getoken()
else: error("Function error: ( expected")
if token.token == idsym: factor()
if token.token == jumpeq:getoken()
if token.token == number:
emit(0, "loadv", token.value)
emit(0, "store", 200)
getoken()
else: error("Function error: assignsym expected")
if token.token == rightbracket:getoken()
else: error("Function error: ) expected")
#return (1);
if token.token == returnvalue:getoken()
else: error("Function error: return expected")
if token.token == leftbracket:getoken()
else: error("Function error: ( expected")
if token.token == number:
emit(0, "loadv", token.value)
emit(0, "store", 201)
getoken()
if token.token == rightbracket:getoken()
else: error("Function error: ) expected")
if token.token == semicolon: getoken()
else: error("Function error: ; expected")
#else{
if token.token == elsesym: getoken()
else: error("Function error: else expected")
if token.token == leftbrace: getoken()
else: error("Function error: { expected")
#factN1=n-1;
if token.token == idsym:
if token.name == "factN1":
print("#Token name:"+token.name+"\n")
getoken()
if token.token == assignsym:getoken()
if token.token == idsym:getoken()
if token.token == minus:
# print("#min"+"\n")
getoken()
if token.token == number:
emit(0, "loadv", token.value)
emit(0, "store", 202)
getoken()
if token.token == semicolon:getoken()
#return(n*fact(factN1));
if token.token == returnvalue:getoken()
if token.token == leftbracket:getoken()
if token.token == idsym: getoken()
if token.token == mpy: getoken()
if token.token == idsym: getoken()
if token.name == "fact":getoken()
if token.token == leftbracket:getoken()
if token.name =="factN1":getoken()
if token.token == rightbracket:getoken()
if token.token == rightbracket:getoken()
if token.token == semicolon:getoken()
#};
if token.token == rightbrace:getoken()
if token.token == semicolon:getoken()
# Compiler main function
#======================================================================
def main():
#======================================================================
global line
global srcfile
global outfile
global charIndex
initSymTbl()
srcfile = open('recursion_function.txt', 'r')
line = srcfile.read() # readline
charIndex = 0
debugScanner = False
if debugScanner: # Scanner Test Routine - Read a line and display the tokens
getoken()
while token.token is not None: # Skeleton for testing Scanner
printToken(token)
# outfile.write(token)
getoken()
sys.exit(1)
else:
getoken() # Parse Program according to the grammar
program() # Call start non-terminal handler
#===============================================================================
# Main Compiler starts here
#===============================================================================
print "#Microcompiler.py v0.2"
"""srcfile = open('recursion_function', 'r')
lexer = shlex.shlex(srcfile)
for token in lexer:
print "#"+repr(token)
"""
emit(0, "load", 0)
emit(100, "constant", "'A'")
emit(101, "constant", "'P'")
emit(102, "constant", "'P'")
emit(103, "constant", "'L'")
emit(104, "constant", "'E'")
emit(105, "constant", "1")
main()
#getoken()
| [
[
8,
0,
0.0032,
0.0053,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
8,
0,
0.0143,
0.0127,
0,
0.66,
0.0185,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0222,
0.0011,
0,
0.66,
... | [
"'''\nCreated on Jun 23, 2014\n\n@author: Brian\n'''",
"\"\"\" Giovanni's MicroCompiler Demo\n\n<program> ::= { <id> ; <vars > <stmtlist> }\n<vars> ::= V { <id> ; } % DECLARATIONS\n\n<stmtlist> ::= <stmt> { ; <stmt> }\n<stmt> ::= P <id> | <id> ... |
'''
Created on Jun 23, 2014
@author: Brian
'''
""" Giovanni's MicroCompiler Demo
<program> ::= { <id> ; <vars > <stmtlist> }
<vars> ::= V { <id> ; } % DECLARATIONS
<stmtlist> ::= <stmt> { ; <stmt> }
<stmt> ::= P <id> | <id> = <expr>
<expr> ::= <factor> { (+ | -) <factor> } % No precedence
<factor> ::= (+|-) ID | Number
"""
import sys
import shlex
#===============================================================================
# # Lexical Analyser - the "Scanner" - Define the TokenTypes
#===============================================================================
tokenNames =\
[ "unknownToken","programsym", "idsym", "assignsym", "leftbrace", "rightbrace","comma",
"varsym","functionsym", "semicolon", "whilesym", "leftbracket", "rightbracket",
"printsym","printmsg", "ifsym", "elsesym","declaresym","forsym", "equals", "notequals", "lessthan", "greaterthan",
"readch", "readint", "writech", "writeint","addup","addup_1",
"number", "plus", "minus", "mpy", "div", "jumpne", "jumpeq","lessthanequal","greaterthanequal","ex","remainder","returnvalue","return_a", "endfile"]
# define the tokens as variables
unknownToken,programsym, idsym, assignsym, leftbrace, rightbrace, comma,\
varsym,functionsym, semicolon, whilesym, leftbracket, rightbracket,\
printsym,printmsg, ifsym, elsesym,declaresym, forsym, equals, notequals, lessthan, greaterthan,\
readch, readint, writech, writeint, addup,addup_1,\
number, plus, minus, mpy, div, jumpne, jumpeq, lessthanequal, greaterthanequal,ex,remainder,returnvalue,return_a, endfile = range(0, len(tokenNames))
#===============================================================================
class symbol:
#===============================================================================
name = None # String representation
token = None; # Corresponding token
address = 0; # For variables, their runtime address
value = None # on defined for numbers
def __init__(self, name, token, value = 0):
self.name = name
self.token = token
self.address = 0 # for identifiers, their address
self.value = value # for numbers, their value
symtbl = {}; # The Symbol Table, a dictionary of symbols indexed by name
#======================================================================
# GLOBALS for output of Lexical Analyser
# Set by each call to GeToken()
token = None; # A symbol
line = "\n" # the complex source file as a string
charIndex = 0 # the position in the source
linenumber= 0 # The current number
EOF = chr(0)
#======================================================================
# Run Time Code Generation Variables
varptr = 500 # Arbitrary base address of memory for variables
codeptr = 10 # Address to output next instruction (for code)
#===============================================================================
# Symbol Table Management Routines
#===============================================================================
#===============================================================================
def addToSymTbl (name, token):
#===============================================================================
symtbl[name] = symbol(name, token) # Add a new symbol to the dictionary
return symtbl[name]
#===============================================================================
def lookup (thisName):
#===============================================================================
"# Find a given identifier in the Symbol Table, Return the symtbl entry"
if symtbl.has_key(thisName): # thisName has been seen before
return symtbl[thisName] # return the symtbl entry
else: return None
#===============================================================================
def initSymTbl():
#===============================================================================
"# Initialise Symbol Table, and preload reserved words"
addToSymTbl('var', varsym) # VAR
addToSymTbl('function', functionsym) # function
addToSymTbl('program', programsym) # function
addToSymTbl('declare', declaresym)
addToSymTbl('while', whilesym) # WHILE
addToSymTbl('for', forsym) # WHILE
addToSymTbl('print', printsym) # PRINT
addToSymTbl('printmsg', printmsg)#PRINTMESSAGE
addToSymTbl('if', ifsym) # IF
addToSymTbl('else', elsesym) # ELSE
addToSymTbl('readint', readint) #READINT
addToSymTbl('writeint', writeint) #READINT
addToSymTbl('readch', readch) #READINT
addToSymTbl('writech', writech) #READINT
addToSymTbl('addup', addup)#ADDUP
addToSymTbl('addup(1)',addup_1)
# Now add symbols - NB only single character symbols are here
# multicharacter one like ">=" are still to do
addToSymTbl( '=', assignsym)
addToSymTbl( '#', notequals)
addToSymTbl( '<', lessthan) #jumplt
addToSymTbl( '>', greaterthan) #jumpgt
addToSymTbl( '{', leftbrace )
addToSymTbl( '}', rightbrace)
addToSymTbl( '(', leftbracket)
addToSymTbl( ')', rightbracket)
addToSymTbl( '+', plus )
addToSymTbl( '-', minus)
addToSymTbl( '*', mpy)
addToSymTbl( '/', div)
addToSymTbl( ';', semicolon)
addToSymTbl( '!', ex)
addToSymTbl( '%', remainder)
addToSymTbl( ',', comma)
addToSymTbl( EOF, endfile)
#multicharacter one like ">=" are still to do
addToSymTbl( '==', jumpeq)
addToSymTbl( '!=', jumpne)
addToSymTbl( '<=', lessthanequal) #jumplt
addToSymTbl( '>=', greaterthanequal) #jumpgt
addToSymTbl( 'return', returnvalue)
addToSymTbl( 'return a', return_a)
#===============================================================================
# Scanner Diagnostics
#===============================================================================
def printToken(tok):
#===============================================================================
" - display the specified token."
if tok.token == idsym:
print "Token = %10s, %-10s adr = %3d" %\
(tokenNames[tok.token], tok.name, tok.address)
elif tok.token == number:
print "Token = %10s %d" % (tokenNames[tok.token], tok.value)
else:
print "Token = %10s" % tokenNames[tok.token]
#==============================?=================================================
def dumpSymTbl():
#===============================================================================
""" Dump all the tokens in the symboltable """
print(" *** Symbol Table ***")
for name in symtbl.keys(): # keys is a list of the names (printable form of tokens)
tok = symtbl[name]
if tok.token == idsym:
printToken(tok)
#===============================================================================
def getch():
#===============================================================================
global line
global charIndex
global linenumber
while True:
if charIndex < len(line): # See if used up current line
ch = line[charIndex] # if not, get character
charIndex = charIndex+1 # & move pointer for next time
else:
#line = srcfile.readline()
if line == "": line = EOF
#print "--> ",
line = raw_input() +"\n" # read new line, adding \n so it's like f.readline()
charIndex = 0 # & reset character pointer
linenumber = linenumber + 1
continue
if ch == "\n":
ch = " " # A newline is a token separator
if ch == "?":
dumpSymTbl()
continue
if ch == "#":
print "#Comment Found"
srcfile.read()
print "#Read next line"
return ch
#===============================================================================
def ungetch():
#===============================================================================
""" Unget the next character peeked at when building variables, numbers
and when distinguishing between >= and > ...
"""
global charIndex;
charIndex = charIndex-1;
#===============================================================================
def getoken():
#===============================================================================
""" GETOKEN - Put next token into the global TOKEN """
global token
ch = getch() # skip whitespace
while ch in ["\t", " ", "\n", "#"]:
ch = getch()
# If ch is alphabetic then this is start of reserved word or an identifier
if ch.isalpha(): # Letter therefore it's either identifier or reserved word
name = ""
while ch.isalpha() or ch.isdigit() or ch == "_":
name = name + ch
ch = getch()
ungetch() # let terminator be used next time
token = lookup(name) # See if token's known
if token is None: # if not
token = addToSymTbl(name, idsym) # add as 'idsym'-IDENTIFIER
return # we've set token.token to either id or tokentype of reserved word
#---------------------------------------------------------------------
# If it's numeric return TOKEN=number & token.value = binary value
elif ch.isdigit():
# In the real version, build number and don't forget to end with ungetch()
token = symbol(ch, number, value = int(ch)) # simplistic SINGLE DIGIT Ascii to Binary
return
#---------------------------------------------------------------------
# Single character tokens
elif ch in [",", "{", "}", "(", ")", "+" , "-", "*", "/", ";","%", EOF]:
token = lookup(ch) # preloaded with appropriate token
# special characters
# check ==
elif ch in ["!"]:
ch = getch()
char = "!"
nEqual = "!="
if ch == "=":
char = nEqual
ch = getch()
else:
token = lookup(ch)
ungetch()
token = lookup(char)
if token is None:
token = addToSymTbl(char, idsym)
return
# check ==
elif ch in ["="]:
ch = getch()
char = "="
Equal = "=="
if ch == "=":
char = Equal
ch = getch()
else:
token = lookup(ch)
ungetch()
token = lookup(char)
if token is None:
token = addToSymTbl(char, idsym)
return
# check <=
elif ch in ["<"]:
ch = getch()
char = "<"
lessthanEqual = "<="
if ch == "=":
char = lessthanEqual
ch = getch()
else:
token = lookup(ch)
ungetch()
token = lookup(char)
if token is None:
token = addToSymTbl(char, idsym)
return
# check >=
elif ch in [">"]:
ch = getch()
char = ">"
greatthanEqual = ">="
if ch == "=":
char = greatthanEqual
ch = getch()
else:
token = lookup(ch)
ungetch()
token = lookup(char)
if token is None:
token = addToSymTbl(char, idsym)
return
elif ch in ["addup"]:
ch = getch()
addup_a = "addup(a)"
if ch == "(":
ch = getch()
if ch == "a":
ch = getch()
if ch == ")":
char = addup_a
else:
token = lookup(ch)
else:
token = lookup(ch)
else:
token = lookup(ch)
ungetch()
token = lookup(char)
if token is None:
token = addToSymTbl(char, idsym)
return
elif token.token ==return_a:
emit(0,"return", 0)
getoken()
else:
print "Unknown character -->%s<- decimal %d" % (ch,ord(ch))
sys.exit(1) # Abort Compilation
#======================================================================
# THE GRAMMAR
# <program> ::= { <id> ; <vars > <stmtlist> }
# <vars> ::= var { <id> ; } % DECLARATIONS
# <array> ::= [<expr>]
# <stmtlist> ::= <stmt> { ; <stmt> }
# <stmt> ::= print <id>
# <id> = <expr>
# <expr> ::= <factor> { (+ | -) <factor> } % No precedence
# <factor> ::= [+/-] ID | Number
#======================================================================
# Centralised Parser Error Message handler
#======================================================================
#===============================================================================
def error (msg):
#===============================================================================
print line
print "-" * charIndex,"^"
print("Error on %d - %s\n" % (number, msg))
printToken(token)
print("\n")
#===============================================================================
def emit (memadr, opcode, parameter):
#===============================================================================
"""EMIT CODE - Emit a of code with a Parameter
if first arg is zero - (the memory address), use and incr CODEPTR"""
global codeptr
if (memadr == 0):
memadr = codeptr
codeptr = codeptr+1
print "%6d %-8s %-7s" % (memadr, opcode, parameter)
#======================================================================
# VARIABLE DECLARATIONS
# <vars> ::= V { <id> ; }
#===============================================================================
def vars() :
#===============================================================================
global varptr;
getoken(); #skip VARSYM - already been recognised
while (token.token == idsym):
if token.address != 0:
print("%c already declared\n", token.name);
else:
symtbl[token.name].address = varptr;
varptr = varptr +1
getoken(); #skip past identifier
if token.token == semicolon: getoken() #skip ;
elif token.token == assignsym: getoken()
else: error("semicolon expected in declaration")
#===============================================================================
def parameters(value1):
#<parameters> ::= (<value>)
#===============================================================================
global va1;
if token.token == leftbracket:getoken();
#1st variable
if token.token == number:
emit(0, "loadv", token.value)
if token.token == rightbracket: getoken();
#======================================================================
# STMTLIST
# <stmtlist> ::= <stmt> { ; <stmt> }
#===============================================================================
def stmtList():
#===============================================================================
stmt()
while (token.token == semicolon):
getoken() #skip ;
stmt()
#======================================================================
# STMT
#===============================================================================
def stmt():
#===============================================================================
""" <stmt> ::= print <expression> | <id> = <expression> | if <expression> | while <expression>
"""
global codeptr
# thisStmtAdr = codeptr # Jump DEMO - not part of Stmt
if token.token == printsym:
printStmt()
elif token.token == printmsg:
printMsg()
elif token.token == addup:
addup()
elif token.token == idsym:
assignStmt()
elif token.token == assignsym:
getoken()
elif token.token == varsym:
vars()
elif token.token == ifsym:
ifStmt()
elif token.token == elsesym:
elseStmt()
elif token.token == whilesym:
whileStmt()
elif token.token == readint:
readIntStmt()
elif token.token == readch:
readChStmt()
elif token.token == writeint:
writeIntStmt()
elif token.token == writech:
writeChStmt()
elif token.token == functionsym:
functionStmt()
elif token.token == rightbrace:
print("")
elif token.token == semicolon:
print("")
else:
error("Expected start of a statement")
# emit (0, "return", thisStmtAdr) # Jump DEMO
#===============================================================================
def printStmt():
#===============================================================================
""" <printStmt> ::= print <expression>"""
getoken() # skip "print"
expression() # on return, expr result (at runtime) will be in ACC
emit(0, "writeint", 0) # Memory address 0 is the ACC
if token.token == rightbrace:
print("#\n*** Compilation finished ***\n")
#===============================================================================
def printMsg():
#===============================================================================
""" <printMsg> ::= printMsg <expression>"""
print("#Print String APPLE to memory")
emit(0, "loadv", 100)
emit(0, "store", 1)
emit(0, "call", 40)
emit(40, "load-Ind", 0)
emit(41, "jumpeq", 45)
emit(42, "writech",150)
emit(43, "increment", 1)
emit(44, "jump", 40)
emit(45, "return", 0)
#===============================================================================
def assignStmt():
#===============================================================================
"""
<id> = <expression>
"""
whichidentifier = token # Remember which ID on Left
getoken() # Get token after identifier
if token.token == notequals: # skip # then read next line
srcfile.read()
getoken()
elif token.token == assignsym: #if the next token is =
expression()
elif token.token == idsym: factor()
elif token.token == jumpeq: print("#")
elif token.token == jumpne: print("#")
elif token.token == lessthanequal: print("")
elif token.token == greaterthanequal: print("")
elif token.token == semicolon: getoken()
else:
error("Expected = in assignment statement")
expression()
# Save result into LHS runtime address
#===============================================================================
def ifStmt():
#if-then-else
#===============================================================================
""" <ifStmt> ::= if <expression>"""
getoken() # skip "if"
emit(0, "compare",60)
expression()
stmt()
emit(0, "return",0)
#===============================================================================
def elseStmt():
#if-then-else
#===============================================================================
""" <elseStmt> ::= else <expression>"""
getoken()
emit(0, "store", 888)
stmt()
#===============================================================================
def whileStmt():
#===============================================================================
""" <whileStmt> ::= while (condition)statement"""
getoken() # skip "if"
emit(0, "compare",50)
expression()
stmt()
emit(0, "increment", 1)
emit(0, "jumpi", 14)
#===============================================================================
def readIntStmt():
#===============================================================================
getoken()
expression() # skip "if"
emit(0, "readint",999)
#===============================================================================
def readChStmt():
#===============================================================================
getoken() # skip "if"
emit(0, "readch",11)
#===============================================================================
def writeIntStmt():
#===============================================================================
getoken() # skip "if"
expression()
emit(0, "writeint",50)
#===============================================================================
def writeChStmt():
#===============================================================================
getoken() # skip "if"
emit(0, "writech",51)
#===============================================================================
def expression():
#===============================================================================
"""
Leaves result in ACC at runtime
Use addresses 999 & 998 as Temporary variables
<expression> ::= <factor> { (+ | - | * | /) <factor> }
"""
factor()
while token.token == plus or token.token == minus:
op = token # remember +/-
getoken() # skip past +/-
emit(0, "store", 1) # Save current result
factor() # Evaluate next factor
#working
if op.token == plus: #+
emit(0, "call", 27)
elif op.token == minus: # - Subtract - have to swap operand order
emit(0, "store", 998)
emit(0, "load" , 999)
emit(0, "subtract", 998) # Leaves result in Acc
emit(0, "store", 880)
#===============================================================================
def factor():
#===============================================================================
"""
# FACTOR() - leaves result in ACC at runtime
<factor> ::= (+|-) identifier | number
"""
#Numbers
if token.token == idsym:
emit(0, "load", token.address)
getoken()
elif token.token == number:
emit(0, "loadv", token.value)
getoken()
elif token.token == assignsym:getoken()
elif token.token == jumpeq:
print("#==")
elif token.token == jumpne:
print("#!=")
elif token.token == lessthanequal:
print("#<=")
elif token.token == greaterthanequal:
print("#<=")
elif token.token == semicolon: getoken()
elif token.token == rightbrace: print("")
else: error("Start of Factor expected")
#===============================================================================
def program():
#===============================================================================
""" # PROGRAM - Start production of the grammar
# <program> <function> ::= { <id> ; <vars > <stmtlist> }
"""
if token.token == programsym:
# print "name",tokenNames[token.token]
getoken()
else: error("Program start with 'program' keyword")
if token.token == idsym: getoken()
else: error("Program error - Program name expected")
if token.token == semicolon: getoken()
else: error("Program error - Semicolon 1 expected")
if token.token == declaresym :
vars()
if token.token == varsym :
vars()
if token.token == functionsym:
functionStmt()
if token.token == addup:
functionStmt()
if token.token == rightbrace:
getoken()
else: error("program error - } expected")
if token.token == semicolon:
getoken()
if token.token == leftbrace:
getoken()
if token.token == printsym:
print("#print")
getoken()
if token.token == leftbracket: #(
getoken()
else: error("program error - ( expected")
#=================================================
# Start Function
#=================================================
if token.token == addup:
functionStmt()
#=================================================
# End Function
#=================================================
if token.token == plus:
getoken()
if token.token == number:
emit(0, "loadv", token.value)
emit(0, "add", 1)
emit(0, "writeInt", 1)
#=================================================
def functionStmt():
#=================================================
# <function> ::= { <id>; <vars > <stmtlist> }
#<parameters>::= <var>, <var>
print("#Start of Function")
getoken(); #skip function - already been recognised
# function name called addup
#combine addup(a) into one token
if token.token == addup: #addup
getoken();
if token.token == leftbracket: #(
getoken()
else: error("Function error: ( expected")
if token.token == number:
emit(0, "loadv", token.value)
emit(0, "store", 1)
emit(0, "call", 27)
getoken()
if token.token == rightbracket:
emit(27, "loadv", 1)
emit(28, "add", 1)
emit(29, "add", 200)
emit(30, "add", 201)
emit(31, "store", 1)
emit(32, "return", 0)
getoken()
# else: error("Function error: rightbracket expected")
if token.token == semicolon:
emit(0, "writeInt", 0)
getoken()
# else: error("Function error: semicolon expected")
if token.token == idsym:
if token.name == "n":
tokenNames[token.token]= "addup_n"
print "#token:-",tokenNames[token.token],"\n"
getoken()
if token.token == rightbracket:getoken()
else: error("Function error: ) expected")
if token.token == semicolon:getoken()
else: error("Function error: semicolon expected")
if token.token == leftbrace:getoken()
else: error("Function error: { expected")
#c=4;
#c aka local variable;
if token.token == idsym:getoken()
else: error("Function error: idsym expected")
if token.token == assignsym:getoken()
else: error("Function error: assignsym expected")
if token.token == number:
emit(0, "loadv", token.value)
emit(0, "store", 200)
getoken()
else: error("Function error: assignsym expected")
if token.token == semicolon:getoken()
else: error("Function error: semicolon expected")
#end of c=4;
#b=6;
#c aka local variable;
if token.token == idsym:getoken()
else: error("Function error: idsym expected")
if token.token == assignsym:getoken()
else: error("Function error: assignsym expected")
if token.token == number:
emit(0, "loadv", token.value)
emit(0, "store", 201)
getoken()
else: error("Function error: assignsym expected")
if token.token == semicolon:getoken()
else: error("Function error: semicolon expected")
#end of c=6;
# n=n+1;
if token.token == idsym:getoken()
else: error("Function error: idsym expected")
if token.token == assignsym:getoken()
else: error("Function error: assignsym expected")
if token.token == idsym:getoken()
else: error("Function error: idsym expected")
if token.token == plus:getoken()
else: error("Function error: plus expected")
if token.token == number:
# emit(0, "loadv", token.value)
getoken()
else: error("Function error: assignsym expected")
if token.token == semicolon:getoken()
else: error("Function error: semicolon expected")
#end of n=n+1;
#return n+c+b;
if token.token == returnvalue:getoken()
else: error("Function error: return expected")
if token.token == idsym:getoken()
else: error("Function error: idsym expected")
if token.token == plus:getoken()
else: error("Function error: plus expected")
if token.token == idsym:getoken()
else: error("Function error: idsym expected")
if token.token == plus:getoken()
else: error("Function error: plus expected")
if token.token == idsym:getoken()
else: error("Function error: idsym expected")
if token.token == semicolon:getoken()
else: error("Function error: semicolon expected")
#end return n+c;
#===============================================================================
def addup_a():
#===============================================================================
"""
emit(27, "add", 1)
emit(28, "return", 0)
"""
if token.token == leftbracket: #(
getoken()
if token.token == idsym:
getoken()
if token.token == number:
emit(0, "loadv", token.value)
emit(0, "store", 1)
getoken()
elif token.token == comma:
getoken()
if token.token == idsym:
getoken()
if token.token == number:
emit(0, "loadv", token.value)
emit(0, "call", 27)
emit(0, "add", 1)
emit(0, "return", 0)
else:emit(0,"return", 0)
if token.token == rightbracket:
getoken()
# Compiler main function
#======================================================================
def main():
#======================================================================
global line
global srcfile
global outfile
global charIndex
initSymTbl()
srcfile = open('function_with_expression.txt', 'r')
line = srcfile.read() # readline
charIndex = 0
debugScanner = False
if debugScanner: # Scanner Test Routine - Read a line and display the tokens
getoken()
while token.token is not None: # Skeleton for testing Scanner
printToken(token)
# outfile.write(token)
getoken()
sys.exit(1)
else:
getoken() # Parse Program according to the grammar
program() # Call start non-terminal handler
#===============================================================================
# Main Compiler starts here
#===============================================================================
print "#Microcompiler.py v0.2"
srcfile = open('function_with_expression.txt', 'r')
lexer = shlex.shlex(srcfile)
for token in lexer:
print "#"+repr(token)
emit(0, "load", 0)
emit(100, "constant", "'A'")
emit(101, "constant", "'P'")
emit(102, "constant", "'P'")
emit(103, "constant", "'L'")
emit(104, "constant", "'E'")
main()
#getoken()
| [
[
8,
0,
0.0032,
0.0053,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
8,
0,
0.0143,
0.0127,
0,
0.66,
0.0182,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0222,
0.0011,
0,
0.66,
... | [
"'''\nCreated on Jun 23, 2014\n\n@author: Brian\n'''",
"\"\"\" Giovanni's MicroCompiler Demo\n\n<program> ::= { <id> ; <vars > <stmtlist> }\n<vars> ::= V { <id> ; } % DECLARATIONS\n\n<stmtlist> ::= <stmt> { ; <stmt> }\n<stmt> ::= P <id> | <id> ... |
import re
__author__ = 'YeeHin Kwok'
""" Giovanni's MicroCompiler Demo
<program> ::= { <id> ; <varDeclare > <stmtlist> }
<varDeclare> ::= V { <id> ; } % DECLARATIONS
<stmtlist> ::= <stmt> { ; <stmt> }
<stmt> ::= P <id> | <id> = <expr>
<expr> ::= <factor> { (+ | -) <factor> } % No precedence
<factor> ::= ID | Number
"""
import sys
import shlex
#===============================================================================
# # Lexical Analyser - the "Scanner" - Define the TokenTypes
#===============================================================================
tokenNames = \
[ "unknownToken", "idsym", "assignsym", "leftbrace", "rightbrace",
"varDeclareym", "semicolon", "whilesym", "leftbracket", "rightbracket",
"printsym", "ifsym", "equals", "lessthan", "greaterthan",
"number", "plus", "minus", "mpy", "div", "elsesym", "declaresym", "forsym", "andsym", "elifsym", "dosym", "returnsym", "notsym",
"continuesym", "breaksym", "nonesym", "programsym", "functionsym", "leftsquarebracket", "rightsquarebracket",
"lessthanequal", "colon", "comma", "comment", "commentstr", "dot", " greaterthanequal", "jumpeq", "jumpne",
"andop", "orop", "quote ", "stringsym", "arraySubsym", "readsym", "endfile"]
# define the tokens as variables
unknownToken, idsym, assignsym, leftbrace, rightbrace, \
varDeclareym, semicolon, whilesym, leftbracket, rightbracket, \
printsym, ifsym, equals, lessthan, greaterthan, \
number, plus, minus, mpy, div, elsesym, declaresym, forsym, andsym, elifsym, dosym, returnsym, notsym, \
continuesym, breaksym, nonesym, programsym, functionsym, leftsquarebracket, rightsquarebracket, \
lessthanequal, colon, comma, comment, commentstr, dot, greaterthanequal, jumpeq, jumpne, \
andop, orop, quote, stringsym, arraySubsym, readsym, endfile = range(0, len(tokenNames))
#===============================================================================
class symbol:
#===============================================================================
name = None # String representation
token = None; # Corresponding token
address = 0; # For variables, their runtime address
value = None # on defined for numbers
def __init__(self, name, token, value=0):
self.name = name
self.token = token
self.address = 0 # for identifiers, their address
self.value = value # for numbers, their value
symtbl = {}; # The Symbol Table, a dictionary of symbols indexed by name
#======================================================================
# GLOBALS for output of Lexical Analyser
# Set by each call to GeToken()
token = None; # A symbol
line = "\n" # the complex source file as a string
charIndex = 0 # the position in the source
linenumber = 0 # The current number
tokennum = 0
resultnum = 0
whichidentifier = None;
identifieraddress = 0;
arraySubaddress = 0;
arrstar = 0;
returnadd = 0;
i = 700
j = 700
counterafter = i
counterafter1 = j
EOF = chr(0)
#======================================================================
# Run Time Code Generation Variables
varptr = 500 # Arbitrary base address of memory for variables
codeptr = 10 # Address to output next instruction (for code)
#===============================================================================
# Symbol Table Management Routines
#===============================================================================
#===============================================================================
def addToSymTbl (name, token):
#===============================================================================
symtbl[name] = symbol(name, token) # Add a new symbol to the dictionary
return symtbl[name]
#===============================================================================
def lookup (thisName):
#===============================================================================
"# Find a given identifier in the Symbol Table, Return the symtbl entry"
if symtbl.has_key(thisName): # thisName has been seen before
return symtbl[thisName] # return the symtbl entry
else: return None
#===============================================================================
def initSymTbl():
#===============================================================================
"# Initialise Symbol Table, and preload reserved words"
addToSymTbl('var', varDeclareym) # VAR
addToSymTbl('program', programsym)
addToSymTbl('function', functionsym)
addToSymTbl('while', whilesym) # WHILE
addToSymTbl('print', printsym) # PRINT
addToSymTbl('else', elsesym)
addToSymTbl('elif', elifsym)
addToSymTbl('if', ifsym)
addToSymTbl('declare', declaresym)
addToSymTbl('for', forsym)
addToSymTbl('None', nonesym)
addToSymTbl('continue', continuesym)
addToSymTbl('read', readsym) # READINT
addToSymTbl('do', dosym)
addToSymTbl('return', returnsym)
addToSymTbl('not', notsym)
# Now add symbols - NB only single character symbols are here
# multicharacter one like ">=" are still to do
addToSymTbl('=', assignsym)
addToSymTbl('#', comment)
addToSymTbl('<', lessthan)
addToSymTbl('>', greaterthan)
addToSymTbl('{', leftbrace)
addToSymTbl('}', rightbrace)
addToSymTbl('(', leftbracket)
addToSymTbl(')', rightbracket)
addToSymTbl('+', plus)
addToSymTbl('-', minus)
addToSymTbl(';', semicolon)
addToSymTbl('break', breaksym)
addToSymTbl('*', mpy)
addToSymTbl('/', div)
addToSymTbl('[', leftsquarebracket)
addToSymTbl(']', rightsquarebracket)
addToSymTbl(':', colon)
addToSymTbl(',', comma)
addToSymTbl('.', dot)
addToSymTbl('==', jumpeq)
addToSymTbl('!=', jumpne)
addToSymTbl('&&', andop)
addToSymTbl('||', orop)
addToSymTbl('"', quote)
addToSymTbl(EOF, endfile)
#===============================================================================
# Scanner Diagnostics
#===============================================================================
def printToken(tok):
#===============================================================================
" - display the specified token."
if tok.token == idsym:
print "Token = %10s, %-10s adr = %3d, val = %d" % \
(tokenNames[tok.token], tok.name, tok.address, tok.value)
elif tok.token == number:
print "Token = %10s %d" % (tokenNames[tok.token], tok.value)
else:
print "Token = %10s" % tokenNames[tok.token]
#==============================?=================================================
def dumpSymTbl():
#===============================================================================
""" Dump all the tokens in the symboltable """
print("# *** Symbol Table ***")
for name in symtbl.keys(): # keys is a list of the names (printable form of tokens)
tok = symtbl[name]
if tok.token == idsym:
print("#"),
printToken(tok)
#===============================================================================
def getch():
#===============================================================================
global line
global charIndex
global linenumber
while True:
if charIndex < len(line): # See if used up current line
ch = line[charIndex] # if not, get character
charIndex = charIndex + 1 # & move pointer for next time
else:
# line = f.readline()
# if line == "": line = EOF
dumpSymTbl()
print "#End of File"
print "#--> ",
line = raw_input() + "\n" # read new line, adding \n so it's like f.readline()
# line = srcfile.read()
charIndex = 0 # & reset character pointer
linenumber = linenumber + 1
continue
if ch == "\n":
ch = " "
if ch == '?':
dumpSymTbl()
continue
return ch
#===============================================================================
def ungetch():
#===============================================================================
""" Unget the next character peeked at when building variables, numbers
and when distinguishing between >= and > ...
"""
global charIndex;
charIndex = charIndex - 1;
#===============================================================================
def getoken():
#===============================================================================
""" GETOKEN - Put next token into the global TOKEN """
global token
global i
global m
global counterafter
global counterafter1
x = 0
ch = getch() # skip whitespace
while ch in ["\t", " ", "\n"]:
ch = getch()
# If ch is alphabetic then this is start of reserved word or an identifier
if ch.isalpha(): # Letter therefore it's either identifier or reserved word
name = ""
while ch.isalpha() or ch.isdigit() or ch == "_":
name = name + ch
ch = getch()
ungetch() # let terminator be used next time
token = lookup(name) # See if token's known
if token is None: # if not
token = addToSymTbl(name, idsym) # add as 'idsym'-IDENTIFIER
return # we've set token.token to either id or tokentype of reserved word
elif ch in ["{", "}", "(", ")", "[", "]", "+", "-", "*", "/", ";", ",", ":", EOF]:
token = lookup(ch) # preloaded with appropriate token
elif ch.isdigit():
# In the real version, build number and don't forget to end with ungetch()
while(ch.isdigit() == True):
x = str(x) + str(ch)
ch = getch()
ch = ungetch()
token = symbol(x, number, value=int(x)) # simplistic SINGLE DIGIT Ascii to Binary
return
elif ch == '#':
str1 = ""
ch = getch()
while ch != " ":
str1 = str(str1) + str(ch)
ch = getch()
ch = getch()
# token = symbol(str1, commentstr, value=str(str1)) # simplistic SINGLE DIGIT Ascii to Binary
print("#comment: " + str(str1))
return
elif ch == '"':
a = ""
ch = getch()
counterafter1 = counterafter
i = counterafter
if counterafter != 700:
counterafter = counterafter + 4;
counterafter = i
while (ch != '"'):
a = str(a) + str(ch)
if ch != " ":
b = "'"+ch+"'"
emit(i, "constant",b)
ch = getch()
else:
ch = getch()
i=i+1
emit(i, "constant", 13)
emit(i+1, "constant", 0)
emit(i+2, "return", '')
ch = getch()
counterafter=i+3
token = symbol(a, stringsym, value=str(a)) # simplistic SINGLE DIGIT Ascii to Binary
return
elif ch == "<":
ch = getch()
if ch == "=":
lt = ""
lt = "<" + "="
token = symbol(lt, lessthanequal, value=str(lt)) # simplistic SINGLE DIGIT Ascii to Binary
return
else:
ch == ungetch()
token = symbol("<", lessthan, value="<") # simplistic SINGLE DIGIT Ascii to Binary
return
elif ch == "!":
ne = ""
ch = getch()
if ch == "=":
ne = "!" + "="
token = symbol(ne, jumpne, value=str(ne)) # simplistic SINGLE DIGIT Ascii to Binary
return
else:
ch == ungetch()
token = symbol("!", NOT , value="!") # simplistic SINGLE DIGIT Ascii to Binary
return
elif ch == "=":
eq = ""
ch = getch()
if ch == "=":
eq = "=" + "="
token = symbol(eq, jumpeq, value=str(eq)) # simplistic SINGLE DIGIT Ascii to Binary
return
else:
ch == ungetch()
token = symbol("=", assignsym, value="=") # simplistic SINGLE DIGIT Ascii to Binary
return
elif ch == ">":
gt = ""
ch = getch()
if ch == "=":
gt = ">" + "="
token = symbol(gt, greaterthanequal, value=str(gt)) # simplistic SINGLE DIGIT Ascii to Binary
return
else:
ch == ungetch()
token = symbol(">", greaterthan, value=">") # simplistic SINGLE DIGIT Ascii to Binary
return
else:
print "Unknown character -->%s<- decimal %d" % (ch, ord(ch))
sys.exit(1) # Abort Compilation
#======================================================================
# THE GRAMMAR
# <program> ::= { <id> ; <varDeclare > <stmtlist> }
# <varDeclare> ::= var { <id> ; } % DECLARATIONS
# <arraySub> ::= [<expr>]
# <stmtlist> ::= <stmt> { ; <stmt> }
# <stmt> ::= print <id>
# <id> = <expr>
# <expr> ::= <term> { (+ | - ) <term> }
# <term> ::= <factor> { (*|/) factor}
# <factor> ::= [+/-] ID | Number | expression
#======================================================================
# Centralised Parser Error Message handler
#======================================================================
#===============================================================================
def error (msg):
#===============================================================================
print line
print "-" * charIndex, "^"
print("Error on %d - %s\n" % (number, msg))
printToken(token)
print("\n")
#===============================================================================
def emit (memadr, opcode, parameter):
#===============================================================================
"""EMIT CODE - Emit a of code with a Parameter
if first arg is zero - (the memory address), use and incr CODEPTR"""
global codeptr
if (memadr == 0):
memadr = codeptr
codeptr = codeptr + 1
print "%6d %-8s %-7s" % (memadr, opcode, parameter)
#===============================================================================
def declareList() :
# declareList ::= varDeclare {, varDeclare};
#===============================================================================
varDeclare()
while token.token != semicolon :
if token.token == comma:
varDeclare()
getoken()
# else: error("comma or semicolon expected in declaration")
#===============================================================================
def varDeclare() :
# varDeclare ::= idsym [ = number | "[" number "]"
#===============================================================================
ta = 0
tn = []
global varptr;
global whichidaddress;
global arraySubaddress;
global arrstar;
getoken();
if token.token == idsym:
ta = token.address
tn = token.name
getoken()
if token.token == leftsquarebracket:
getoken()
if token.token == number: #number
print("#The address for "+ str(tn)+ " are ")
symtbl[tn].address = varptr;
# emit(0, "constant", varptr)
print("#"+str(varptr))
while (token.value != 0):
# print("#address at " + str(varptr))
varptr = varptr + 1
token.value= token.value-1
# emit(0, "constant", varptr)
print("#"+str(varptr))
# getoken()
getoken()
if token.token == rightsquarebracket:
getoken()
else:
error("Expected rightsquarebracket at the end of arraySub declare")
else:
if ta != 0:
print("#"),
print("%c already declared\n", tn);
# assignStmt()
else:
symtbl[tn].address = varptr;
varptr = varptr + 1;
# emit(0, "load", varptr)
"""
if token.token == assignsym:
getoken()
if token.token == number:
arraySubaddress = arrstar+token.value
whichidaddress = arraySubaddress
print"#"+"arraySub address", str(arraySubaddress)
getoken()
if token.token == rightsquarebracket:
stmt()
# getoken()
getoken()
"""
# if token.token == leftsquarebracket:
# varDeclare()
# getoken()
# if token.token == rightbracket:
# getoken()
#===============================================================================
def variable():
# idsym [arraySub]
#===============================================================================
if token.token == idsym:
arraySub()
#===============================================================================
def arraySub():
# [expression]
#===============================================================================
global arraySub;
expression()
#===============================================================================
def parameters():
#===============================================================================
varDeclare()
# getoken()
#======================================================================
# STMTLIST
# <stmtlist> ::= <stmt> { ; <stmt> }
#===============================================================================
def stmtList():
#===============================================================================
stmt()
while (token.token != rightbrace):
stmt()
#======================================================================
# STMT
#===============================================================================
def stmt():
#===============================================================================
""" <stmt> ::= print <expression|string>| read <varDeclare> | <id> = <expression> |
if <condition> <stmt> [else <stmt>]| while <condition> <stmt>|
<stmtList> | do <stmsList> forever | break | continue
"""
global codeptr
thisStmtAdr = codeptr # Jump DEMO - not part of Stmt
# if token.token == arraySubsym:
# arraySub()
if token.token == varDeclare:
getoken()
if token.token == assignsym:
expression()
else:
parameter()
elif token.token == ifsym:
ifStmt()
# elif token.token == elsesym:
# elseStmt()
elif token.token == whilesym:
whileStmt()
elif token.token == stmtList:
stmtList()
elif token.token == printsym:
printStmt()
elif token.token == readsym:
readStmt()
elif token.token == declaresym:
declareList()
elif token.token == dosym:
doStmt()
elif token.token == breaksym:
emit(0, "halt", '')
elif token.token == continuesym:
continueStmt()
elif token.token == number:
expression()
elif token.token == idsym:
assignStmt()
elif token.token == functionsym:
function()
elif token.token == returnsym:
returnStmt()
else:
error("Expected start of a statement")
if token.token == semicolon or token.token == comma:
getoken()
#===============================================================================
def printStmt():
#===============================================================================
""" <printStmt> ::= print <expression|string>"""
global idaddress
getoken() # skip "print"
if token.token == leftbracket:
getoken()
else:
error("Expected leftbracket before the print-item")
# printta = token.address
print_item()
if token.token == comma:
print_item()
getoken()
if token.token == rightbracket:
getoken()
# if token.token == rightbracket:
# getoken()
# else:
# error("Expected rightbracket end the print")
if token.token == semicolon:
getoken()
# else:
# error("Expected semicolon end the print")
#===============================================================================
def print_item():
# expression | string
#===============================================================================
# expression
if token.token == idsym:
expression()
emit(0, "writeint", 0)
getoken()
# string
if token.token == stringsym:
printMsg()
getoken()
#===============================================================================
def printMsg():
#===============================================================================
""" <printMsg> ::= printMsg <expression>"""
emit(0, "loadv", counterafter1)
emit(0, "store", 1)
emit(0, "call", 400)
emit(400, "load-Ind", 0)
emit(401, "jumpeq", 405)
emit(402, "writech", 0)
emit(403, "increment", 1)
emit(404, "jump", 400)
emit(405, "return", '')
#===============================================================================
def readStmt():
#===============================================================================
""" <readStmt> ::= read variable()"""
global idaddress
getoken()
if token.token == leftbracket:
getoken()
else:
error("Expected leftbracket before the variable")
variable()
emit(0, "readint", idaddress)
if token.token == rightbracket:
getoken()
else:
error("Expected rightbracket after the variable")
#===============================================================================
def assignStmt():
#===============================================================================
"""
<id> = <expression>
"""
global tokennum
global resultnum
global whichidentifier
global whichidaddress
global arraySubaddress
whichidentifier = token.name # Remember which ID on Left
tempadd = token.address
if arraySubaddress != 0:
whichidaddress = token.address;
else:
whichidaddress = arraySubaddress;
getoken() # Get token after identifier
if token.token == assignsym:
getoken()
else:
error("Expected = in assignment statement")
expression()
passtoken = token.value
# print(str(whichidaddress))
emit(0, "store", tempadd)
"""
if whichidaddress == 0:
# print("#tokenaddress " + str(tempadd))
emit(0, "store", tempadd)
else:
symtbl[whichidentifier].value = tokennum
# print("#whichidaddress "+str(whichidaddress))
emit(0, "store", whichidaddress)
"""
getoken()
#===============================================================================
def ifStmt():
# <ifStmt> ::= if (condition) statement [else statement]
#===============================================================================
getoken() # skip "if"
if token.token == leftbracket:
getoken()
else:
error("Expected leftbracket at the start of if-condition")
condition()
# getoken()
if token.token == rightbracket:
getoken()
else:
error("Expected rightbracket at the end of if-condition")
if token.token == leftbrace:
getoken()
else:
error("Expected leftbrace at the start of if-statement")
stmt()
# emit(0, "halt", '')
getoken()
if token.token == rightbrace:
getoken()
# else:
# error("Expected rightbrace at the end of if-statement")
if token.token == elsesym:
getoken()
if token.token == leftbrace:
getoken()
else:
error("Expected leftbrace at the start of else-statement")
stmt()
# emit(0, "halt", '')
if token.token == rightbrace:
getoken()
else:
error("Expected rightbrace at the end of else-statement")
#===============================================================================
def whileStmt():
#===============================================================================
""" <whileStmt> ::= while (condition)statement"""
getoken()# skip "while"
if token.token == leftbracket:
getoken()
else:
error("Expected leftbracket at the start of while-condition")
condition()
if token.token == rightbracket:
getoken()
else:
error("Expected rightbracket at the end of while-condition")
if token.token == leftbrace:
getoken()
else:
error("Expected leftbrace at the start of while-statement")
stmt()
if token.token == rightbrace:
getoken()
else:
error("Expected rightbrace at the end of while-statement")
#===============================================================================
def doStmt():
#===============================================================================
getoken()
stmtList()
#===============================================================================
def returnStmt():
#===============================================================================
# global returnadd;
getoken()
if token.token == leftbracket:
getoken()
if token.token == idsym:
expression()
print("#"+str(token.value))
emit(0, "jump", 0)
if token.token == rightbracket:
getoken()
else:
error("Expected rightbracket for return-statement")
#===============================================================================
def condition():
# [not] conditional-expression
#===============================================================================
notsign = False;
if token.token == notsym:
notsign = True;
getoken()
if notsign == True:
emit(0, "Not", '')
conditionalexp()
else:
conditionalexp()
#===============================================================================
def conditionalexp():
#===============================================================================
expression()
relational_op()
# getoken()
# expression()
#===============================================================================
def relational_op():
#===============================================================================
if token.token == lessthan or token.token == greaterthan or token.token == lessthanequal or token.token == greaterthanequal or token.token == jumpne or token.token == jumpeq:
op = token # remember -
getoken() # skip past -
emit(0, "store", 686) # Save current expression result
term()
if op.token == lessthan:
emit(0, "store", 1)
emit(0, "load", 686)
emit(0, "compare", 1)
emit(0, "jumplt", 37)
elif op.token == greaterthan:
emit(0, "compare", 686)
emit(0, "jumpgt", 0)
# emit(0, "jump", 131)
elif op.token == lessthanequal:
emit(0, "compare", 686)
emit(0, "jumplt", 43)
emit(0, "jumpeq", 43)
elif op.token == greaterthanequal:
emit(0, "compare", 686)
emit(0, "jumpgt", 43)
emit(0, "jumpeq", 43)
elif op.token == jumpne:
emit(0, "compare", 686)
emit(0, "jumpne", 310)
elif op.token == jumpeq:
emit(0, "compare", 686)
emit(0, "jumpeq", 133)
emit(0, "jump", 138)
#===============================================================================
def expression():
#===============================================================================
"""
Leaves result in ACC at runtime
Use addresses 999 & 688 as Temporary variables
<expression> ::= <factor> { (+ | -) <factor> } <- wrong
<expression> ::= <term> { (+ | -) <term> }
"""
global whichidentifier
global idaddress
global idvalue
if whichidentifier == None:
getoken()
else:
idaddress = symtbl[whichidentifier].address
idvalue = symtbl[whichidentifier].value
if token.token == leftbracket:
getoken()
term()
## 1st start==============================================================================
while token.token == plus or token.token == minus:
op = token # remember -
getoken() # skip past -
emit(0, "store", 687) # Save current result
term()
if op.token == plus:
emit(0, "add", 687)
elif op.token == minus: # Subtract - have to swap operand order
emit(0, "store", 1)
emit(0, "load", 687)
emit(0, "subtract", 1)
#===============================================================================
def term():
#===============================================================================
"""
term::= factor {(*|/) factor}
"""
global idaddress
factor()
while token.token == mpy or token.token == div:
op = token # remember -
getoken() # skip past -
emit(0, "store", 688) # Save term result
# save here xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
factor()
if op.token == mpy:
emit(0, "mpy", 688)
elif op.token == div:
emit(0, "store", 1)
emit(0, "load",688)
emit(0, "div", 1)
#===============================================================================
def factor():
#===============================================================================
"""
# FACTOR() - leaves result in ACC at runtime
<factor> ::= [+|-] identifier | number | (expression)
"""
global tokennum
global whichidentifier
global idaddress
global idvalue
tokensign = False
# [+|-] number
if token.token == plus:
getoken()
# - (unary)
elif token.token == minus:
tokensign=True
getoken()
elif token.token == number:
if tokensign == True:
emit(0, "loadv", 0 - token.value)
getoken()
else:
emit(0, "loadv", token.value)
tokennum = token.value
getoken()
# identifier
elif token.token == idsym:
emit(0, "load", token.address)
idaddress = token.address
tempaddress = token.address
# print(str(tempaddress))
getoken()
if token.token == leftbracket:
getoken()
expression()
emit(0, "store", tempaddress+2)
emit(0, "call", 210)
if token.token == rightbracket:
getoken()
else:
error("Expected rightbracket after the factor")
else:
error("Start Of Factor Expected")
#===============================================================================
def function():
#===============================================================================
global returnadd;
global codeptr
beginaddress = codeptr
# print(str(beginaddress))
codeptr = codeptr+200
getoken()
if token.token == idsym:
getoken()
if token.token == leftbracket:
getoken()
if token.token == idsym:
parameters()
# elif token.token == number:
# print("#"+str(token.value))
else:
error("Function error : No_parameter_input_for_function")
if token.token == rightbracket:
getoken()
else:
error("Expected rightbracket for parameter")
if token.token == semicolon:
getoken()
else:
error("Expected semicolon after parameter")
if token.token == declaresym:
declareList()
"""
if token.token == semicolon:
getoken()
else:
error("Expected semicolon after declare variable")
"""
if token.token == leftbrace:
getoken()
stmtList()
if token.token == rightbrace:
getoken()
print ("#---Function Finished---")
codeptr = beginaddress
#===============================================================================
def program():
#===============================================================================
if token.token == leftbrace:
getoken()
if token.token == programsym:
getoken()
else: error("Program start with 'program' keyword")
if token.token == idsym:
getoken()
if token.token == semicolon:
getoken()
if token.token == declaresym :
declareList()
if token.token == functionsym:
function()
if token.token == leftbrace:
getoken()
stmtList()
if token.token == rightbrace:
print "#***Compilation Finished****"
#======================================================================
def main():
#======================================================================
global line
global srcfile
global charIndex
initSymTbl()
with open("test.txt") as srcfile:
# out1file = open('output.obj','w')
line = srcfile.read()
# out1file.write("hello")
# print line
charIndex = 0
debugScanner = False
if debugScanner: # Scanner Test Routine - Read a line and display the tokens
getoken()
while token.token is not None: # Skeleton for testing Scanner
printToken(token)
# y = str(token)
# out1file.write(y)
getoken()
sys.exit(1)
else:
getoken() # Parse Program according to the grammar
program()
#===============================================================================
# Main Compiler starts here
#===============================================================================
print "#Microcompiler.py v0.2"
#emit(0, "load", 0)
main()
"""
srcfile = open('test.txt', 'r')
lexer = shlex.shlex(srcfile)
for token in lexer:
print repr(token)
"""
# getoken()
#=======================================================================
# *** That's it folks - written by Giovanni Moretti - April 27, 2011 ***
#=======================================================================
| [
[
1,
0,
0.0008,
0.0008,
0,
0.66,
0,
540,
0,
1,
0,
0,
540,
0,
0
],
[
14,
0,
0.0025,
0.0008,
0,
0.66,
0.0156,
777,
1,
0,
0,
0,
0,
3,
0
],
[
8,
0,
0.0103,
0.0099,
0,
0... | [
"import re",
"__author__ = 'YeeHin Kwok'",
"\"\"\" Giovanni's MicroCompiler Demo\n\n<program> ::= { <id> ; <varDeclare > <stmtlist> }\n<varDeclare> ::= V { <id> ; } % DECLARATIONS\n\n<stmtlist> ::= <stmt> { ; <stmt> }\n<stmt> ::= P <id> | <id... |
import math
def sieve_of_atkin(limit):
results = [2, 3, 5]
sieve = [False]*(limit+1)
factor = int(math.sqrt(limit))+1
for i in range(1, factor):
for j in range(1, factor):
n = 4*i**2+j**2
if (n <= limit) and (n % 12 == 1 or n % 12 == 5):
sieve[n] = not sieve[n]
n = 3*i**2+j**2
if (n <= limit) and (n % 12 == 7):
sieve[n] = not sieve[n]
if i > j:
n = 3*i**2-j**2
if (n <= limit) and (n % 12 == 11):
sieve[n] = not sieve[n]
for index in range(5, factor):
if sieve[index]:
for jndex in range(index**2, limit, index**2):
sieve[jndex] = False
for index in range(7, limit):
if sieve[index]:
results.append(index)
return results | [
[
1,
0,
0.037,
0.037,
0,
0.66,
0,
526,
0,
1,
0,
0,
526,
0,
0
],
[
2,
0,
0.5741,
0.8889,
0,
0.66,
1,
196,
0,
1,
1,
0,
0,
0,
8
],
[
14,
1,
0.1852,
0.037,
1,
0.25,
... | [
"import math",
"def sieve_of_atkin(limit):\n results = [2, 3, 5]\n sieve = [False]*(limit+1)\n factor = int(math.sqrt(limit))+1\n for i in range(1, factor):\n for j in range(1, factor):\n n = 4*i**2+j**2\n if (n <= limit) and (n % 12 == 1 or n % 12 == 5):",
" results ... |
import struct
import Atkin
import random
from array import array
class MyException (Exception): pass
#m = 11*19 # large primes should be used
#xi = 0
'''
def eratosthenes(n):
multiples = []
primes1 = []
for i in range(2, n+1):
if i not in multiples:
primes1.append(i)
for j in range(i*i, n+1, i):
multiples.append(j)
return primes1
'''
'''
primes = Atkin.sieve_of_atkin(10000)
def get_primes():
global primes
out_primes = []
while len(out_primes) < 2:
curr_prime = primes.pop()
if curr_prime % 4 == 3:
out_primes.append(curr_prime)
return out_primes
primes = get_primes()
m = primes[0]*primes[1]
'''
'''
def blum_blum_shub_generator():
global xi
xi = ((xi+1)**2)%m
return
'''
primes = Atkin.sieve_of_atkin(1000)
def gen_primes():
global primes
out_primes = []
while len(out_primes) < 2:
curr_prime = primes[random.randrange(len(primes))]
if curr_prime % 4 == 3:
out_primes.append(curr_prime)
return out_primes
# random generator must return only ONE number
x = random.randrange(1000000)
def random_generator(length1):
global x
while length1:
x += 1
p, q = gen_primes()
m1 = p * q
z = (x**2) % m1
length1 -= 1
yield str(bin(z).count('1') % 2)
def get_random_bits():
return ''.join(random_generator(1))
#for i in range(1000000):
# print(blum_blum_shub_generator())
frame_ = get_random_bits()
length = 3000000
#frame.append(get_random_bits())
#fo.write(frame)
#fo.close()
fob = open("lkmb.txt", "wb")
#foc = open("lkmc.txt", "w")
try:
#for i in range(0, 3000000):
# nn = blum_blum_shub_generator()
# fob.write(struct.pack("I", nn))
# foc.write(str(nn)+"\n")
fob.write(frame)
fob.close()
#foc.close()
except MyException: print("except, motherfucker") | [
[
1,
0,
0.0103,
0.0103,
0,
0.66,
0,
399,
0,
1,
0,
0,
399,
0,
0
],
[
1,
0,
0.0206,
0.0103,
0,
0.66,
0.0625,
690,
0,
1,
0,
0,
690,
0,
0
],
[
1,
0,
0.0309,
0.0103,
0,
... | [
"import struct",
"import Atkin",
"import random",
"from array import array",
"class MyException (Exception): pass",
"'''\n\ndef eratosthenes(n):\n multiples = []\n primes1 = []\n for i in range(2, n+1):\n if i not in multiples:",
"'''\nprimes = Atkin.sieve_of_atkin(10000)\n\n\ndef get_pr... |
import math
""""
int CACHE = 30000; // размер кэша
int M = (int)Math.sqrt(N)+1;
int primes = new int[P]; // массив простых чисел до корня из N
boolean segment = new boolean[CACHE]; // вторичное решето
for (int I=M-1; I < N; I+=CACHE) {
Arrays.fill(segment, true);
for (int i= 0; i < P; i++) {
int h = I % primes[i];
int j = h > 0 ? primes[i] - h : 0;
for (; j < CACHE; j+=primes[i])
segment[j] = false;
}
for (int i= 0; i<CACHE; i++) {
if (segment[i] && (i + I < N)) {
out.println(i+I); // выводим простое число на экран
}
}
}
"""
def sieveOfErat(end):
if end < 2: return []
#The array doesn't need to include even numbers
lng = ((end/2)-1+end%2)
# Create array and assume all numbers in array are prime
sieve = [True]*(lng+1)
# In the following code, you're going to see some funky
# bit shifting and stuff, this is just transforming i and j
# so that they represent the proper elements in the array.
# The transforming is not optimal, and the number of
# operations involved can be reduced.
# Only go up to square root of the end
for i in range(int(sqrt(end)) >> 1):
# Skip numbers that aren’t marked as prime
if not sieve[i]: continue
# Unmark all multiples of i, starting at i**2
for j in range( (i*(i + 3) << 1) + 3, lng, (i << 1) + 3):
sieve[j] = False
# Don't forget 2!
primes = [2]
# Gather all the primes into a list, leaving out the composite numbers
primes.extend([(i << 1) + 3 for i in range(lng) if sieve[i]])
return primes
n = 10
CACHE = 30000
M = int(math.sqrt(n)+1)
prime = []
segment = []
for i in range(M-1):
for tr in range(0, CACHE):
segment.append(True)
print(segment) | [
[
1,
0,
0.0145,
0.0145,
0,
0.66,
0,
526,
0,
1,
0,
0,
526,
0,
0
],
[
8,
0,
0.1884,
0.3043,
0,
0.66,
0.1111,
0,
1,
0,
0,
0,
0,
0,
0
],
[
2,
0,
0.587,
0.4638,
0,
0.66,... | [
"import math",
"\"\"\"\"\nint CACHE = 30000; // размер кэша\nint M = (int)Math.sqrt(N)+1;\n\nint primes = new int[P]; // массив простых чисел до корня из N\nboolean segment = new boolean[CACHE]; // вторичное решето\nfor (int I=M-1; I < N; I+=CACHE) {\n Arrays.fill(segment, true);",
"def sieveOfErat(end):... |
#====================================================================
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# ====================================================================
#
# This software consists of voluntary contributions made by many
# individuals on behalf of the Apache Software Foundation. For more
# information on the Apache Software Foundation, please see
# <http://www.apache.org/>.
#
import os
import re
import tempfile
import shutil
ignore_pattern = re.compile('^(.svn|target|bin|classes)')
java_pattern = re.compile('^.*\.java')
annot_pattern = re.compile('import org\.apache\.http\.annotation\.')
def process_dir(dir):
files = os.listdir(dir)
for file in files:
f = os.path.join(dir, file)
if os.path.isdir(f):
if not ignore_pattern.match(file):
process_dir(f)
else:
if java_pattern.match(file):
process_source(f)
def process_source(filename):
tmp = tempfile.mkstemp()
tmpfd = tmp[0]
tmpfile = tmp[1]
try:
changed = False
dst = os.fdopen(tmpfd, 'w')
try:
src = open(filename)
try:
for line in src:
if annot_pattern.match(line):
changed = True
line = line.replace('import org.apache.http.annotation.', 'import net.jcip.annotations.')
dst.write(line)
finally:
src.close()
finally:
dst.close();
if changed:
shutil.move(tmpfile, filename)
else:
os.remove(tmpfile)
except:
os.remove(tmpfile)
process_dir('.')
| [
[
1,
0,
0.3514,
0.0135,
0,
0.66,
0,
688,
0,
1,
0,
0,
688,
0,
0
],
[
1,
0,
0.3649,
0.0135,
0,
0.66,
0.1111,
540,
0,
1,
0,
0,
540,
0,
0
],
[
1,
0,
0.3784,
0.0135,
0,
... | [
"import os",
"import re",
"import tempfile",
"import shutil",
"ignore_pattern = re.compile('^(.svn|target|bin|classes)')",
"java_pattern = re.compile('^.*\\.java')",
"annot_pattern = re.compile('import org\\.apache\\.http\\.annotation\\.')",
"def process_dir(dir):\n files = os.listdir(dir)\n for... |
#!/usr/bin/python2.6
#
# Simple http server to emulate api.playfoursquare.com
import logging
import shutil
import sys
import urlparse
import SimpleHTTPServer
import BaseHTTPServer
class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
"""Handle playfoursquare.com requests, for testing."""
def do_GET(self):
logging.warn('do_GET: %s, %s', self.command, self.path)
url = urlparse.urlparse(self.path)
logging.warn('do_GET: %s', url)
query = urlparse.parse_qs(url.query)
query_keys = [pair[0] for pair in query]
response = self.handle_url(url)
if response != None:
self.send_200()
shutil.copyfileobj(response, self.wfile)
self.wfile.close()
do_POST = do_GET
def handle_url(self, url):
path = None
if url.path == '/v1/venue':
path = '../captures/api/v1/venue.xml'
elif url.path == '/v1/addvenue':
path = '../captures/api/v1/venue.xml'
elif url.path == '/v1/venues':
path = '../captures/api/v1/venues.xml'
elif url.path == '/v1/user':
path = '../captures/api/v1/user.xml'
elif url.path == '/v1/checkcity':
path = '../captures/api/v1/checkcity.xml'
elif url.path == '/v1/checkins':
path = '../captures/api/v1/checkins.xml'
elif url.path == '/v1/cities':
path = '../captures/api/v1/cities.xml'
elif url.path == '/v1/switchcity':
path = '../captures/api/v1/switchcity.xml'
elif url.path == '/v1/tips':
path = '../captures/api/v1/tips.xml'
elif url.path == '/v1/checkin':
path = '../captures/api/v1/checkin.xml'
elif url.path == '/history/12345.rss':
path = '../captures/api/v1/feed.xml'
if path is None:
self.send_error(404)
else:
logging.warn('Using: %s' % path)
return open(path)
def send_200(self):
self.send_response(200)
self.send_header('Content-type', 'text/xml')
self.end_headers()
def main():
if len(sys.argv) > 1:
port = int(sys.argv[1])
else:
port = 8080
server_address = ('0.0.0.0', port)
httpd = BaseHTTPServer.HTTPServer(server_address, RequestHandler)
sa = httpd.socket.getsockname()
print "Serving HTTP on", sa[0], "port", sa[1], "..."
httpd.serve_forever()
if __name__ == '__main__':
main()
| [
[
1,
0,
0.0588,
0.0118,
0,
0.66,
0,
715,
0,
1,
0,
0,
715,
0,
0
],
[
1,
0,
0.0706,
0.0118,
0,
0.66,
0.125,
614,
0,
1,
0,
0,
614,
0,
0
],
[
1,
0,
0.0824,
0.0118,
0,
0... | [
"import logging",
"import shutil",
"import sys",
"import urlparse",
"import SimpleHTTPServer",
"import BaseHTTPServer",
"class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):\n \"\"\"Handle playfoursquare.com requests, for testing.\"\"\"\n\n def do_GET(self):\n logging.warn('do_GET: %s, %s',... |
#!/usr/bin/python
import os
import subprocess
import sys
BASEDIR = '../main/src/com/joelapenna/foursquare'
TYPESDIR = '../captures/types/v1'
captures = sys.argv[1:]
if not captures:
captures = os.listdir(TYPESDIR)
for f in captures:
basename = f.split('.')[0]
javaname = ''.join([c.capitalize() for c in basename.split('_')])
fullpath = os.path.join(TYPESDIR, f)
typepath = os.path.join(BASEDIR, 'types', javaname + '.java')
parserpath = os.path.join(BASEDIR, 'parsers', javaname + 'Parser.java')
cmd = 'python gen_class.py %s > %s' % (fullpath, typepath)
print cmd
subprocess.call(cmd, stdout=sys.stdout, shell=True)
cmd = 'python gen_parser.py %s > %s' % (fullpath, parserpath)
print cmd
subprocess.call(cmd, stdout=sys.stdout, shell=True)
| [
[
1,
0,
0.1111,
0.037,
0,
0.66,
0,
688,
0,
1,
0,
0,
688,
0,
0
],
[
1,
0,
0.1481,
0.037,
0,
0.66,
0.1429,
394,
0,
1,
0,
0,
394,
0,
0
],
[
1,
0,
0.1852,
0.037,
0,
0.6... | [
"import os",
"import subprocess",
"import sys",
"BASEDIR = '../main/src/com/joelapenna/foursquare'",
"TYPESDIR = '../captures/types/v1'",
"captures = sys.argv[1:]",
"if not captures:\n captures = os.listdir(TYPESDIR)",
" captures = os.listdir(TYPESDIR)",
"for f in captures:\n basename = f.split('... |
#!/usr/bin/python
"""
Pull a oAuth protected page from foursquare.
Expects ~/.oget to contain (one on each line):
CONSUMER_KEY
CONSUMER_KEY_SECRET
USERNAME
PASSWORD
Don't forget to chmod 600 the file!
"""
import httplib
import os
import re
import sys
import urllib
import urllib2
import urlparse
import user
from xml.dom import pulldom
from xml.dom import minidom
import oauth
"""From: http://groups.google.com/group/foursquare-api/web/oauth
@consumer = OAuth::Consumer.new("consumer_token","consumer_secret", {
:site => "http://foursquare.com",
:scheme => :header,
:http_method => :post,
:request_token_path => "/oauth/request_token",
:access_token_path => "/oauth/access_token",
:authorize_path => "/oauth/authorize"
})
"""
SERVER = 'api.foursquare.com:80'
CONTENT_TYPE_HEADER = {'Content-Type' :'application/x-www-form-urlencoded'}
SIGNATURE_METHOD = oauth.OAuthSignatureMethod_HMAC_SHA1()
AUTHEXCHANGE_URL = 'http://api.foursquare.com/v1/authexchange'
def parse_auth_response(auth_response):
return (
re.search('<oauth_token>(.*)</oauth_token>', auth_response).groups()[0],
re.search('<oauth_token_secret>(.*)</oauth_token_secret>',
auth_response).groups()[0]
)
def create_signed_oauth_request(username, password, consumer):
oauth_request = oauth.OAuthRequest.from_consumer_and_token(
consumer, http_method='POST', http_url=AUTHEXCHANGE_URL,
parameters=dict(fs_username=username, fs_password=password))
oauth_request.sign_request(SIGNATURE_METHOD, consumer, None)
return oauth_request
def main():
url = urlparse.urlparse(sys.argv[1])
# Nevermind that the query can have repeated keys.
parameters = dict(urlparse.parse_qsl(url.query))
password_file = open(os.path.join(user.home, '.oget'))
lines = [line.strip() for line in password_file.readlines()]
if len(lines) == 4:
cons_key, cons_key_secret, username, password = lines
access_token = None
else:
cons_key, cons_key_secret, username, password, token, secret = lines
access_token = oauth.OAuthToken(token, secret)
consumer = oauth.OAuthConsumer(cons_key, cons_key_secret)
if not access_token:
oauth_request = create_signed_oauth_request(username, password, consumer)
connection = httplib.HTTPConnection(SERVER)
headers = {'Content-Type' :'application/x-www-form-urlencoded'}
connection.request(oauth_request.http_method, AUTHEXCHANGE_URL,
body=oauth_request.to_postdata(), headers=headers)
auth_response = connection.getresponse().read()
token = parse_auth_response(auth_response)
access_token = oauth.OAuthToken(*token)
open(os.path.join(user.home, '.oget'), 'w').write('\n'.join((
cons_key, cons_key_secret, username, password, token[0], token[1])))
oauth_request = oauth.OAuthRequest.from_consumer_and_token(consumer,
access_token, http_method='POST', http_url=url.geturl(),
parameters=parameters)
oauth_request.sign_request(SIGNATURE_METHOD, consumer, access_token)
connection = httplib.HTTPConnection(SERVER)
connection.request(oauth_request.http_method, oauth_request.to_url(),
body=oauth_request.to_postdata(), headers=CONTENT_TYPE_HEADER)
print connection.getresponse().read()
#print minidom.parse(connection.getresponse()).toprettyxml(indent=' ')
if __name__ == '__main__':
main()
| [
[
8,
0,
0.0631,
0.0991,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.1261,
0.009,
0,
0.66,
0.05,
2,
0,
1,
0,
0,
2,
0,
0
],
[
1,
0,
0.1351,
0.009,
0,
0.66,
0.... | [
"\"\"\"\nPull a oAuth protected page from foursquare.\n\nExpects ~/.oget to contain (one on each line):\nCONSUMER_KEY\nCONSUMER_KEY_SECRET\nUSERNAME\nPASSWORD",
"import httplib",
"import os",
"import re",
"import sys",
"import urllib",
"import urllib2",
"import urlparse",
"import user",
"from xml.... |
#!/usr/bin/python
import datetime
import sys
import textwrap
import common
from xml.dom import pulldom
PARSER = """\
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquare.parsers;
import com.joelapenna.foursquare.Foursquare;
import com.joelapenna.foursquare.error.FoursquareError;
import com.joelapenna.foursquare.error.FoursquareParseException;
import com.joelapenna.foursquare.types.%(type_name)s;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Auto-generated: %(timestamp)s
*
* @author Joe LaPenna (joe@joelapenna.com)
* @param <T>
*/
public class %(type_name)sParser extends AbstractParser<%(type_name)s> {
private static final Logger LOG = Logger.getLogger(%(type_name)sParser.class.getCanonicalName());
private static final boolean DEBUG = Foursquare.PARSER_DEBUG;
@Override
public %(type_name)s parseInner(XmlPullParser parser) throws XmlPullParserException, IOException,
FoursquareError, FoursquareParseException {
parser.require(XmlPullParser.START_TAG, null, null);
%(type_name)s %(top_node_name)s = new %(type_name)s();
while (parser.nextTag() == XmlPullParser.START_TAG) {
String name = parser.getName();
%(stanzas)s
} else {
// Consume something we don't understand.
if (DEBUG) LOG.log(Level.FINE, "Found tag that we don't recognize: " + name);
skipSubTree(parser);
}
}
return %(top_node_name)s;
}
}"""
BOOLEAN_STANZA = """\
} else if ("%(name)s".equals(name)) {
%(top_node_name)s.set%(camel_name)s(Boolean.valueOf(parser.nextText()));
"""
GROUP_STANZA = """\
} else if ("%(name)s".equals(name)) {
%(top_node_name)s.set%(camel_name)s(new GroupParser(new %(sub_parser_camel_case)s()).parse(parser));
"""
COMPLEX_STANZA = """\
} else if ("%(name)s".equals(name)) {
%(top_node_name)s.set%(camel_name)s(new %(parser_name)s().parse(parser));
"""
STANZA = """\
} else if ("%(name)s".equals(name)) {
%(top_node_name)s.set%(camel_name)s(parser.nextText());
"""
def main():
type_name, top_node_name, attributes = common.WalkNodesForAttributes(
sys.argv[1])
GenerateClass(type_name, top_node_name, attributes)
def GenerateClass(type_name, top_node_name, attributes):
"""generate it.
type_name: the type of object the parser returns
top_node_name: the name of the object the parser returns.
per common.WalkNodsForAttributes
"""
stanzas = []
for name in sorted(attributes):
typ, children = attributes[name]
replacements = Replacements(top_node_name, name, typ, children)
if typ == common.BOOLEAN:
stanzas.append(BOOLEAN_STANZA % replacements)
elif typ == common.GROUP:
stanzas.append(GROUP_STANZA % replacements)
elif typ in common.COMPLEX:
stanzas.append(COMPLEX_STANZA % replacements)
else:
stanzas.append(STANZA % replacements)
if stanzas:
# pop off the extranious } else for the first conditional stanza.
stanzas[0] = stanzas[0].replace('} else ', '', 1)
replacements = Replacements(top_node_name, name, typ, [None])
replacements['stanzas'] = '\n'.join(stanzas).strip()
print PARSER % replacements
def Replacements(top_node_name, name, typ, children):
# CameCaseClassName
type_name = ''.join([word.capitalize() for word in top_node_name.split('_')])
# CamelCaseClassName
camel_name = ''.join([word.capitalize() for word in name.split('_')])
# camelCaseLocalName
attribute_name = camel_name.lower().capitalize()
# mFieldName
field_name = 'm' + camel_name
if children[0]:
sub_parser_camel_case = children[0] + 'Parser'
else:
sub_parser_camel_case = (camel_name[:-1] + 'Parser')
return {
'type_name': type_name,
'name': name,
'top_node_name': top_node_name,
'camel_name': camel_name,
'parser_name': typ + 'Parser',
'attribute_name': attribute_name,
'field_name': field_name,
'typ': typ,
'timestamp': datetime.datetime.now(),
'sub_parser_camel_case': sub_parser_camel_case,
'sub_type': children[0]
}
if __name__ == '__main__':
main()
| [
[
1,
0,
0.0201,
0.0067,
0,
0.66,
0,
426,
0,
1,
0,
0,
426,
0,
0
],
[
1,
0,
0.0268,
0.0067,
0,
0.66,
0.0769,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.0336,
0.0067,
0,
... | [
"import datetime",
"import sys",
"import textwrap",
"import common",
"from xml.dom import pulldom",
"PARSER = \"\"\"\\\n/**\n * Copyright 2009 Joe LaPenna\n */\n\npackage com.joelapenna.foursquare.parsers;\n\nimport com.joelapenna.foursquare.Foursquare;",
"BOOLEAN_STANZA = \"\"\"\\\n } else i... |
#!/usr/bin/python
import logging
from xml.dom import minidom
from xml.dom import pulldom
BOOLEAN = "boolean"
STRING = "String"
GROUP = "Group"
# Interfaces that all FoursquareTypes implement.
DEFAULT_INTERFACES = ['FoursquareType']
# Interfaces that specific FoursqureTypes implement.
INTERFACES = {
}
DEFAULT_CLASS_IMPORTS = [
]
CLASS_IMPORTS = {
# 'Checkin': DEFAULT_CLASS_IMPORTS + [
# 'import com.joelapenna.foursquare.filters.VenueFilterable'
# ],
# 'Venue': DEFAULT_CLASS_IMPORTS + [
# 'import com.joelapenna.foursquare.filters.VenueFilterable'
# ],
# 'Tip': DEFAULT_CLASS_IMPORTS + [
# 'import com.joelapenna.foursquare.filters.VenueFilterable'
# ],
}
COMPLEX = [
'Group',
'Badge',
'Beenhere',
'Checkin',
'CheckinResponse',
'City',
'Credentials',
'Data',
'Mayor',
'Rank',
'Score',
'Scoring',
'Settings',
'Stats',
'Tags',
'Tip',
'User',
'Venue',
]
TYPES = COMPLEX + ['boolean']
def WalkNodesForAttributes(path):
"""Parse the xml file getting all attributes.
<venue>
<attribute>value</attribute>
</venue>
Returns:
type_name - The java-style name the top node will have. "Venue"
top_node_name - unadultured name of the xml stanza, probably the type of
java class we're creating. "venue"
attributes - {'attribute': 'value'}
"""
doc = pulldom.parse(path)
type_name = None
top_node_name = None
attributes = {}
level = 0
for event, node in doc:
# For skipping parts of a tree.
if level > 0:
if event == pulldom.END_ELEMENT:
level-=1
logging.warn('(%s) Skip end: %s' % (str(level), node))
continue
elif event == pulldom.START_ELEMENT:
logging.warn('(%s) Skipping: %s' % (str(level), node))
level+=1
continue
if event == pulldom.START_ELEMENT:
logging.warn('Parsing: ' + node.tagName)
# Get the type name to use.
if type_name is None:
type_name = ''.join([word.capitalize()
for word in node.tagName.split('_')])
top_node_name = node.tagName
logging.warn('Found Top Node Name: ' + top_node_name)
continue
typ = node.getAttribute('type')
child = node.getAttribute('child')
# We don't want to walk complex types.
if typ in COMPLEX:
logging.warn('Found Complex: ' + node.tagName)
level = 1
elif typ not in TYPES:
logging.warn('Found String: ' + typ)
typ = STRING
else:
logging.warn('Found Type: ' + typ)
logging.warn('Adding: ' + str((node, typ)))
attributes.setdefault(node.tagName, (typ, [child]))
logging.warn('Attr: ' + str((type_name, top_node_name, attributes)))
return type_name, top_node_name, attributes
| [
[
1,
0,
0.0263,
0.0088,
0,
0.66,
0,
715,
0,
1,
0,
0,
715,
0,
0
],
[
1,
0,
0.0439,
0.0088,
0,
0.66,
0.0833,
290,
0,
1,
0,
0,
290,
0,
0
],
[
1,
0,
0.0526,
0.0088,
0,
... | [
"import logging",
"from xml.dom import minidom",
"from xml.dom import pulldom",
"BOOLEAN = \"boolean\"",
"STRING = \"String\"",
"GROUP = \"Group\"",
"DEFAULT_INTERFACES = ['FoursquareType']",
"INTERFACES = {\n}",
"DEFAULT_CLASS_IMPORTS = [\n]",
"CLASS_IMPORTS = {\n# 'Checkin': DEFAULT_CLASS_IMP... |
#!/usr/bin/python
import cgi
import cgitb
cgitb.enable()
import os
print "Content-Type: text/html\n"
print "<html>"
print "<head><title>Quad 20 in CGI"
print "</title></head>"
print "<body>"
for e in range(1,21):
print str(e*e)+'</br>'
print "</body></html>"
| [
[
1,
0,
0.2143,
0.0714,
0,
0.66,
0,
934,
0,
1,
0,
0,
934,
0,
0
],
[
1,
0,
0.2857,
0.0714,
0,
0.66,
0.1,
691,
0,
1,
0,
0,
691,
0,
0
],
[
8,
0,
0.3571,
0.0714,
0,
0.6... | [
"import cgi",
"import cgitb",
"cgitb.enable()",
"import os",
"print(\"Content-Type: text/html\\n\")",
"print(\"<html>\")",
"print(\"<head><title>Quad 20 in CGI\")",
"print(\"</title></head>\")",
"print(\"<body>\")",
"for e in range(1,21):\n\tprint(str(e*e)+'</br>')",
"\tprint(str(e*e)+'</br>')",... |
#!/usr/bin/python
print "Content-Type: text/html\n"
import os, random, cgi, cgitb
cgitb.enable()
i = 0
c=0
richtig = 0
erg = 0
a= random.randint(1,11)
b= random.randint(1,11)
form = cgi.FieldStorage()
if "i" in form: i = int(form["i"].value)
if "erg" in form: erg = int(form["erg"].value)
if "c" in form: c = int(form["c"].value)
if "richtig" in form: richtig = int(form["richtig"].value)
print "<html>"
print "<head><title>Kopfrechner</title></head>"
print '<form action="kopfrechentrainer.cgi" method="POST">'
#print '<form action="kopfrechentrainer.cgi" method="GET">'
print "<p>"
if(i!=0):
if c == erg:
richtig+=1
if i<6:
print "Loesen sie bitte folgende Aufgabe:"
if i<3:
print a,"+",b,"= ?"
c = a+b
i+=1
else:
print a,"*",b,"= ?"
c = a*b
i+=1
else:
print "Sie haben ",richtig,"von",i," Aufgaben richtig."
if i <=6:
print '<br/>Ihre eingabe: <input type="text" name="erg">'
print '<input type="hidden" name="i" value=',i,'>'
print '<input type="hidden" name="c" value=',c,'>'
print '<input type="hidden" name="richtig" value=',richtig,'>'
print '<input type="submit" name="ok" value="ok">'
print "</p>"
print "</html>"
| [
[
8,
0,
0.0652,
0.0217,
0,
0.66,
0,
535,
3,
1,
0,
0,
0,
0,
1
],
[
1,
0,
0.087,
0.0217,
0,
0.66,
0.0455,
688,
0,
4,
0,
0,
688,
0,
0
],
[
8,
0,
0.1087,
0.0217,
0,
0.6... | [
"print(\"Content-Type: text/html\\n\")",
"import os, random, cgi, cgitb",
"cgitb.enable()",
"i = 0",
"c=0",
"richtig = 0",
"erg = 0",
"a= random.randint(1,11)",
"b= random.randint(1,11)",
"form = cgi.FieldStorage()",
"if \"i\" in form: i = int(form[\"i\"].value)",
"if \"i\" in form: i = int(fo... |
#!/usr/bin/python
print "Content-Type: text/html\n"
import os
l = os.environ["HTTP_ACCEPT_LANGUAGE"].split(";")
if "en" in l[0]:
print "Hello World"
else:
print "Hallo Welt"
| [
[
8,
0,
0.25,
0.0833,
0,
0.66,
0,
535,
3,
1,
0,
0,
0,
0,
1
],
[
1,
0,
0.4167,
0.0833,
0,
0.66,
0.3333,
688,
0,
1,
0,
0,
688,
0,
0
],
[
14,
0,
0.5833,
0.0833,
0,
0.6... | [
"print(\"Content-Type: text/html\\n\")",
"import os",
"l = os.environ[\"HTTP_ACCEPT_LANGUAGE\"].split(\";\")",
"if \"en\" in l[0]:\n\tprint(\"Hello World\")\nelse:\n\tprint(\"Hallo Welt\")",
"\tprint(\"Hello World\")",
"\tprint(\"Hallo Welt\")"
] |
#!/usr/bin/python
print "Content-Type: text/html\n"
import os, random, cgi, cgitb
cgitb.enable()
i = 0
c=0
richtig = 0
erg = 0
a= random.randint(1,11)
b= random.randint(1,11)
form = cgi.FieldStorage()
if "i" in form: i = int(form["i"].value)
if "erg" in form: erg = int(form["erg"].value)
if "c" in form: c = int(form["c"].value)
if "richtig" in form: richtig = int(form["richtig"].value)
print "<html>"
print "<head><title>Kopfrechner</title></head>"
print '<form action="kopfrechentrainer.cgi" method="POST">'
#print '<form action="kopfrechentrainer.cgi" method="GET">'
print "<p>"
if(i!=0):
if c == erg:
richtig+=1
if i<6:
print "Loesen sie bitte folgende Aufgabe:"
if i<3:
print a,"+",b,"= ?"
c = a+b
i+=1
else:
print a,"*",b,"= ?"
c = a*b
i+=1
else:
print "Sie haben ",richtig,"von",i," Aufgaben richtig."
if i <=6:
print '<br/>Ihre eingabe: <input type="text" name="erg">'
print '<input type="hidden" name="i" value=',i,'>'
print '<input type="hidden" name="c" value=',c,'>'
print '<input type="hidden" name="richtig" value=',richtig,'>'
print '<input type="submit" name="ok" value="ok">'
print "</p>"
print "</html>"
| [
[
8,
0,
0.0652,
0.0217,
0,
0.66,
0,
535,
3,
1,
0,
0,
0,
0,
1
],
[
1,
0,
0.087,
0.0217,
0,
0.66,
0.0455,
688,
0,
4,
0,
0,
688,
0,
0
],
[
8,
0,
0.1087,
0.0217,
0,
0.6... | [
"print(\"Content-Type: text/html\\n\")",
"import os, random, cgi, cgitb",
"cgitb.enable()",
"i = 0",
"c=0",
"richtig = 0",
"erg = 0",
"a= random.randint(1,11)",
"b= random.randint(1,11)",
"form = cgi.FieldStorage()",
"if \"i\" in form: i = int(form[\"i\"].value)",
"if \"i\" in form: i = int(fo... |
#!/usr/bin/python
print "Content-Type: text/html\n"
import cgi
import cgitb
cgitb.enable()
import os
form = cgi.FieldStorage()
n = 20
if "n" in form: n = form["n"].value
print "<html>"
print "<head><title>n Quadratzahlen"
print "</title></head>"
print "<body>"
for e in range(1,int(n)+1):
print str(e*e)+'</br>'
print "</body></html>"
| [
[
8,
0,
0.1,
0.05,
0,
0.66,
0,
535,
3,
1,
0,
0,
0,
0,
1
],
[
1,
0,
0.15,
0.05,
0,
0.66,
0.0769,
934,
0,
1,
0,
0,
934,
0,
0
],
[
1,
0,
0.2,
0.05,
0,
0.66,
0.1538... | [
"print(\"Content-Type: text/html\\n\")",
"import cgi",
"import cgitb",
"cgitb.enable()",
"import os",
"form = cgi.FieldStorage()",
"n = 20",
"if \"n\" in form: n = form[\"n\"].value",
"if \"n\" in form: n = form[\"n\"].value",
"print(\"<html>\")",
"print(\"<head><title>n Quadratzahlen\")",
"pr... |
#!/usr/bin/python
print "Content-Type: text/html\n"
import os, sys, random
directory = "/usr/share/games/fortunes/"
l = os.listdir(directory)
b = []
for e in l:
if ".u8" not in e and ".dat" not in e and "de" not in e:
b.append(e)
s = ""
for e in b:
f = open(directory+e)
s+=f.read()
f.close()
bla = s.split("\n%\n")
c = []
print "<html><head><title>Little funny fortunes</title></head>"
print "<body>"
print "<form>"
if os.environ.has_key("QUERY_STRING"):
st = os.environ["QUERY_STRING"].split("m=")
if len(st)==1:
print '<p>Suchwort:<br><input name="m" type="text" size="30" maxlength="30">'
print '<input type="submit" value=" Absenden "></p>'
if len(st)==2:
print '<p>Suchwort:<br><input name="m" type="text" size="30" maxlength="30" value = ',st[1],'>'
print '<input type="submit" value=" Absenden "></p>'
for e in bla:
if st[1] in e:
c.append(e)
if len(c)>0:
print c[random.randint(0,len(c)-1)]
else:
print 'No fortune found with "',st[1],'"'
else:
print bla[random.randint(0,len(bla)-1)]
print "</form>"
print "</body>"
print "</html>"
| [
[
8,
0,
0.0625,
0.0208,
0,
0.66,
0,
535,
3,
1,
0,
0,
0,
0,
1
],
[
1,
0,
0.1042,
0.0208,
0,
0.66,
0.0625,
688,
0,
3,
0,
0,
688,
0,
0
],
[
14,
0,
0.125,
0.0208,
0,
0.... | [
"print(\"Content-Type: text/html\\n\")",
"import os, sys, random",
"directory = \"/usr/share/games/fortunes/\"",
"l = os.listdir(directory)",
"b = []",
"for e in l:\n if \".u8\" not in e and \".dat\" not in e and \"de\" not in e:\n b.append(e)",
" if \".u8\" not in e and \".dat\" not in e a... |
#!/usr/bin/python
print "Content-Type: text/html\n"
print "<html>"
print "<head><title>Hallo CGI-Python"
print "</title></head>"
print "<body>"
print "Hello CGI Python"
print "</body></html>"
| [
[
8,
0,
0.2222,
0.1111,
0,
0.66,
0,
535,
3,
1,
0,
0,
0,
0,
1
],
[
8,
0,
0.4444,
0.1111,
0,
0.66,
0.1667,
535,
3,
1,
0,
0,
0,
0,
1
],
[
8,
0,
0.5556,
0.1111,
0,
0.66... | [
"print(\"Content-Type: text/html\\n\")",
"print(\"<html>\")",
"print(\"<head><title>Hallo CGI-Python\")",
"print(\"</title></head>\")",
"print(\"<body>\")",
"print(\"Hello CGI Python\")",
"print(\"</body></html>\")"
] |
#!/usr/bin/python
import cgi
import cgitb
cgitb.enable()
import os
print "Content-Type: text/html\n"
print "<html>"
print "<head><title>Quad 20 in CGI"
print "</title></head>"
print "<body>"
for e in range(1,21):
print str(e*e)+'</br>'
print "</body></html>"
| [
[
1,
0,
0.2143,
0.0714,
0,
0.66,
0,
934,
0,
1,
0,
0,
934,
0,
0
],
[
1,
0,
0.2857,
0.0714,
0,
0.66,
0.1,
691,
0,
1,
0,
0,
691,
0,
0
],
[
8,
0,
0.3571,
0.0714,
0,
0.6... | [
"import cgi",
"import cgitb",
"cgitb.enable()",
"import os",
"print(\"Content-Type: text/html\\n\")",
"print(\"<html>\")",
"print(\"<head><title>Quad 20 in CGI\")",
"print(\"</title></head>\")",
"print(\"<body>\")",
"for e in range(1,21):\n\tprint(str(e*e)+'</br>')",
"\tprint(str(e*e)+'</br>')",... |
#!/usr/bin/python
print "Content-Type: text/html\n"
print "Hallo CGI-Welt"
| [
[
8,
0,
0.5,
0.25,
0,
0.66,
0,
535,
3,
1,
0,
0,
0,
0,
1
],
[
8,
0,
1,
0.25,
0,
0.66,
1,
535,
3,
1,
0,
0,
0,
0,
1
]
] | [
"print(\"Content-Type: text/html\\n\")",
"print(\"Hallo CGI-Welt\")"
] |
#!/usr/bin/python
print "Content-Type: text/html\n"
import os
l = os.environ["HTTP_ACCEPT_LANGUAGE"].split(";")
if "en" in l[0]:
print "Hello World"
else:
print "Hallo Welt"
| [
[
8,
0,
0.25,
0.0833,
0,
0.66,
0,
535,
3,
1,
0,
0,
0,
0,
1
],
[
1,
0,
0.4167,
0.0833,
0,
0.66,
0.3333,
688,
0,
1,
0,
0,
688,
0,
0
],
[
14,
0,
0.5833,
0.0833,
0,
0.6... | [
"print(\"Content-Type: text/html\\n\")",
"import os",
"l = os.environ[\"HTTP_ACCEPT_LANGUAGE\"].split(\";\")",
"if \"en\" in l[0]:\n\tprint(\"Hello World\")\nelse:\n\tprint(\"Hallo Welt\")",
"\tprint(\"Hello World\")",
"\tprint(\"Hallo Welt\")"
] |
#!/usr/bin/python
print "Content-Type: text/html\n"
import os
for key in os.environ:
print key, "="
print os.environ[key], "<br />"
if os.environ.has_key("QUERY_STRING"):
print os.environ["QUERY_STRING"]
| [
[
8,
0,
0.25,
0.0833,
0,
0.66,
0,
535,
3,
1,
0,
0,
0,
0,
1
],
[
1,
0,
0.4167,
0.0833,
0,
0.66,
0.3333,
688,
0,
1,
0,
0,
688,
0,
0
],
[
6,
0,
0.6667,
0.25,
0,
0.66,
... | [
"print(\"Content-Type: text/html\\n\")",
"import os",
"for key in os.environ:\n\tprint(key, \"=\")\n\tprint(os.environ[key], \"<br />\")",
"\tprint(key, \"=\")",
"\tprint(os.environ[key], \"<br />\")",
"if os.environ.has_key(\"QUERY_STRING\"):\n\tprint(os.environ[\"QUERY_STRING\"])",
"\tprint(os.environ... |
#!/usr/bin/python
print "Content-Type: text/html\n"
import os
for key in os.environ:
print key, "="
print os.environ[key], "<br />"
if os.environ.has_key("QUERY_STRING"):
print os.environ["QUERY_STRING"]
| [
[
8,
0,
0.25,
0.0833,
0,
0.66,
0,
535,
3,
1,
0,
0,
0,
0,
1
],
[
1,
0,
0.4167,
0.0833,
0,
0.66,
0.3333,
688,
0,
1,
0,
0,
688,
0,
0
],
[
6,
0,
0.6667,
0.25,
0,
0.66,
... | [
"print(\"Content-Type: text/html\\n\")",
"import os",
"for key in os.environ:\n\tprint(key, \"=\")\n\tprint(os.environ[key], \"<br />\")",
"\tprint(key, \"=\")",
"\tprint(os.environ[key], \"<br />\")",
"if os.environ.has_key(\"QUERY_STRING\"):\n\tprint(os.environ[\"QUERY_STRING\"])",
"\tprint(os.environ... |
#!/usr/bin/python
print "Content-Type: text/html\n"
print "<html>"
print "<head><title>Hallo CGI-Python"
print "</title></head>"
print "<body>"
print "Hello CGI Python"
print "</body></html>"
| [
[
8,
0,
0.2222,
0.1111,
0,
0.66,
0,
535,
3,
1,
0,
0,
0,
0,
1
],
[
8,
0,
0.4444,
0.1111,
0,
0.66,
0.1667,
535,
3,
1,
0,
0,
0,
0,
1
],
[
8,
0,
0.5556,
0.1111,
0,
0.66... | [
"print(\"Content-Type: text/html\\n\")",
"print(\"<html>\")",
"print(\"<head><title>Hallo CGI-Python\")",
"print(\"</title></head>\")",
"print(\"<body>\")",
"print(\"Hello CGI Python\")",
"print(\"</body></html>\")"
] |
#!/usr/bin/python
print "Content-Type: text/html\n"
import cgi
import cgitb
cgitb.enable()
import os
form = cgi.FieldStorage()
n = 20
if "n" in form: n = form["n"].value
print "<html>"
print "<head><title>n Quadratzahlen"
print "</title></head>"
print "<body>"
for e in range(1,int(n)+1):
print str(e*e)+'</br>'
print "</body></html>"
| [
[
8,
0,
0.1,
0.05,
0,
0.66,
0,
535,
3,
1,
0,
0,
0,
0,
1
],
[
1,
0,
0.15,
0.05,
0,
0.66,
0.0769,
934,
0,
1,
0,
0,
934,
0,
0
],
[
1,
0,
0.2,
0.05,
0,
0.66,
0.1538... | [
"print(\"Content-Type: text/html\\n\")",
"import cgi",
"import cgitb",
"cgitb.enable()",
"import os",
"form = cgi.FieldStorage()",
"n = 20",
"if \"n\" in form: n = form[\"n\"].value",
"if \"n\" in form: n = form[\"n\"].value",
"print(\"<html>\")",
"print(\"<head><title>n Quadratzahlen\")",
"pr... |
#!/usr/bin/python
print "Content-Type: text/html\n"
print "Hallo CGI-Welt"
| [
[
8,
0,
0.5,
0.25,
0,
0.66,
0,
535,
3,
1,
0,
0,
0,
0,
1
],
[
8,
0,
1,
0.25,
0,
0.66,
1,
535,
3,
1,
0,
0,
0,
0,
1
]
] | [
"print(\"Content-Type: text/html\\n\")",
"print(\"Hallo CGI-Welt\")"
] |
#!/usr/bin/python
print "Content-Type: text/html\n"
import os, sys, random
directory = "/usr/share/games/fortunes/"
l = os.listdir(directory)
b = []
for e in l:
if ".u8" not in e and ".dat" not in e and "de" not in e:
b.append(e)
s = ""
for e in b:
f = open(directory+e)
s+=f.read()
f.close()
bla = s.split("\n%\n")
c = []
print "<html><head><title>Little funny fortunes</title></head>"
print "<body>"
print "<form>"
if os.environ.has_key("QUERY_STRING"):
st = os.environ["QUERY_STRING"].split("m=")
if len(st)==1:
print '<p>Suchwort:<br><input name="m" type="text" size="30" maxlength="30">'
print '<input type="submit" value=" Absenden "></p>'
if len(st)==2:
print '<p>Suchwort:<br><input name="m" type="text" size="30" maxlength="30" value = ',st[1],'>'
print '<input type="submit" value=" Absenden "></p>'
for e in bla:
if st[1] in e:
c.append(e)
if len(c)>0:
print c[random.randint(0,len(c)-1)]
else:
print 'No fortune found with "',st[1],'"'
else:
print bla[random.randint(0,len(bla)-1)]
print "</form>"
print "</body>"
print "</html>"
| [
[
8,
0,
0.0625,
0.0208,
0,
0.66,
0,
535,
3,
1,
0,
0,
0,
0,
1
],
[
1,
0,
0.1042,
0.0208,
0,
0.66,
0.0625,
688,
0,
3,
0,
0,
688,
0,
0
],
[
14,
0,
0.125,
0.0208,
0,
0.... | [
"print(\"Content-Type: text/html\\n\")",
"import os, sys, random",
"directory = \"/usr/share/games/fortunes/\"",
"l = os.listdir(directory)",
"b = []",
"for e in l:\n if \".u8\" not in e and \".dat\" not in e and \"de\" not in e:\n b.append(e)",
" if \".u8\" not in e and \".dat\" not in e a... |
#!/usr/bin/python
import cgi
import cgitb
cgitb.enable()
print "Content-Type: text/html\n"
print "<html>"
print "<body>"
for a in range(1,21):
print str(a**2)+'<br/>'
print "</body>"
print "</html>"
| [
[
1,
0,
0.1765,
0.0588,
0,
0.66,
0,
934,
0,
1,
0,
0,
934,
0,
0
],
[
1,
0,
0.2353,
0.0588,
0,
0.66,
0.125,
691,
0,
1,
0,
0,
691,
0,
0
],
[
8,
0,
0.2941,
0.0588,
0,
0... | [
"import cgi",
"import cgitb",
"cgitb.enable()",
"print(\"Content-Type: text/html\\n\")",
"print(\"<html>\")",
"print(\"<body>\")",
"for a in range(1,21):\n print(str(a**2)+'<br/>')",
" print(str(a**2)+'<br/>')",
"print(\"</body>\")",
"print(\"</html>\")"
] |
#!/usr/bin/python
import cgi
import cgitb
import random
cgitb.enable()
form = cgi.FieldStorage()
x = random.randint(1, 10)
y = random.randint(1, 10)
z = 0
erg = 0
right = 0
if form.has_key("Zaehler"):
z = z + int(form["Zaehler"].value)
z=z+1
if z < 4 :
erg = x + y
o = '+'
else :
erg = x * y
o = '*'
if form.has_key("Richtige"):
right = right + int(form["Richtige"].value)
if form.has_key("Eingabe"):
#if "Eingabe" in form: #funktioniert auch so :D
if form["Eingabe"].value==form["Ergebnis"].value:
right = right +1
print "Content-Type: text/html\n"
print "<html>"
print "<body>"
print "<head><title>Kopfrechner</title></head>"
if z <=6:
print "%i %s %i" % (x, o, y)
print "<form action='kopfrechner.cgi' method='POST'>"
print "Ihre Loesung:<br><input name='Eingabe' type='text' size='10' maxlength='4'/>"
print "<input type='submit' value='Senden' />"
print "<input type='hidden' name='ErsteZahl' value='%i'>" % x
print "<input type='hidden' name='ZweiteZahl' value='%i'>" % y
print "<input type='hidden' name='Zaehler' value=",z,">"
print "<input type='hidden' name='Ergebnis' value='%i'>" %erg
print "<input type='hidden' name='Richtige' value='%i'>" %right
print "</form>"
else:
print "Sie haben %i von %i Aufgaben richtig geloest." % (right, z-1)
print "</body>"
print "</html>"
| [
[
1,
0,
0.0508,
0.0169,
0,
0.66,
0,
934,
0,
1,
0,
0,
934,
0,
0
],
[
1,
0,
0.0678,
0.0169,
0,
0.66,
0.0476,
691,
0,
1,
0,
0,
691,
0,
0
],
[
1,
0,
0.0847,
0.0169,
0,
... | [
"import cgi",
"import cgitb",
"import random",
"cgitb.enable()",
"form = cgi.FieldStorage()",
"x = random.randint(1, 10)",
"y = random.randint(1, 10)",
"z = 0",
"erg = 0",
"right = 0",
"if form.has_key(\"Zaehler\"):\n z = z + int(form[\"Zaehler\"].value)",
" z = z + int(form[\"Zaehler\"]... |
#!/usr/bin/python
import os
print "Content-Type: text/html\n"
for key in os.environ:
print key, "="
print os.environ[key], "<br />" | [
[
1,
0,
0.4286,
0.1429,
0,
0.66,
0,
688,
0,
1,
0,
0,
688,
0,
0
],
[
8,
0,
0.5714,
0.1429,
0,
0.66,
0.5,
535,
3,
1,
0,
0,
0,
0,
1
],
[
6,
0,
0.8571,
0.4286,
0,
0.66,... | [
"import os",
"print(\"Content-Type: text/html\\n\")",
"for key in os.environ:\n print(key, \"=\")\n print(os.environ[key], \"<br />\")",
" print(key, \"=\")",
" print(os.environ[key], \"<br />\")"
] |
#!/usr/bin/python
import os
import cgi
import cgitb
cgitb.enable()
print "Content-Type: text/html\n"
print "<html>"
print "<head><title>Hallo Tim</title></head>"
print "<body>"
if os.environ["HTTP_ACCEPT_LANGUAGE"][:2]=='en':
print "Hello World!"
else:
print "Hallo Welt!"
print "</body>"
print "</html>"
| [
[
1,
0,
0.1667,
0.0556,
0,
0.66,
0,
688,
0,
1,
0,
0,
688,
0,
0
],
[
1,
0,
0.2222,
0.0556,
0,
0.66,
0.1,
934,
0,
1,
0,
0,
934,
0,
0
],
[
1,
0,
0.2778,
0.0556,
0,
0.6... | [
"import os",
"import cgi",
"import cgitb",
"cgitb.enable()",
"print(\"Content-Type: text/html\\n\")",
"print(\"<html>\")",
"print(\"<head><title>Hallo Tim</title></head>\")",
"print(\"<body>\")",
"if os.environ[\"HTTP_ACCEPT_LANGUAGE\"][:2]=='en': \n print(\"Hello World!\")\nelse:... |
#!/usr/bin/python
import cgi
import cgitb
cgitb.enable()
print "Content-Type: text/html\n"
print "<html>"
print "<body>"
form = cgi.FieldStorage()
if form.has_key("n"):
n = form.getvalue("n")
for a in range(1,int(n)+1):
print str(a**2)+'<br/>'
else:
n = 21
for a in range(1,n):
print str(a**2)+'<br/>'
print "</body>"
print "</html>"
| [
[
1,
0,
0.1071,
0.0357,
0,
0.66,
0,
934,
0,
1,
0,
0,
934,
0,
0
],
[
1,
0,
0.1429,
0.0357,
0,
0.66,
0.1111,
691,
0,
1,
0,
0,
691,
0,
0
],
[
8,
0,
0.1786,
0.0357,
0,
... | [
"import cgi",
"import cgitb",
"cgitb.enable()",
"print(\"Content-Type: text/html\\n\")",
"print(\"<html>\")",
"print(\"<body>\")",
"form = cgi.FieldStorage()",
"if form.has_key(\"n\"):\n\n n = form.getvalue(\"n\")\n \n for a in range(1,int(n)+1):\n print(str(a**2)+'<br/>')\n\nelse:... |
#!/usr/bin/python
import cgi
import cgitb
import fortune
cgitb.enable()
print "Content-Type: text/html\n"
print "<html>"
print "<body>"
print "<head><title>Fortune</title></head>"
form = cgi.FieldStorage()
if form.has_key("m"):
#m = form["m"].value //alternative
m = form.getvalue("m")
print fortune.getQuote(m)
else:
m=""
print fortune.getRandomQuote()
print "<form action='fortune.cgi'>"
print "In Zitat enthalten: <br>\n"
print "<input name='m' type='text' size='30' maxlength='30' value=",m,">"
print "<input type='Submit' value='Ok'>"
print "</form>"
print "</body>"
print "</html>"
| [
[
1,
0,
0.0938,
0.0312,
0,
0.66,
0,
934,
0,
1,
0,
0,
934,
0,
0
],
[
1,
0,
0.125,
0.0312,
0,
0.66,
0.0625,
691,
0,
1,
0,
0,
691,
0,
0
],
[
1,
0,
0.1562,
0.0312,
0,
0... | [
"import cgi",
"import cgitb",
"import fortune",
"cgitb.enable()",
"print(\"Content-Type: text/html\\n\")",
"print(\"<html>\")",
"print(\"<body>\")",
"print(\"<head><title>Fortune</title></head>\")",
"form = cgi.FieldStorage()",
"if form.has_key(\"m\"):\n #m = form[\"m\"].value //alternative\n ... |
#!/usr/bin/python
import cgi
import cgitb
import random
cgitb.enable()
form = cgi.FieldStorage()
x = random.randint(1, 10)
y = random.randint(1, 10)
z = 0
erg = 0
right = 0
if form.has_key("Zaehler"):
z = z + int(form["Zaehler"].value)
z=z+1
if z < 4 :
erg = x + y
o = '+'
else :
erg = x * y
o = '*'
if form.has_key("Richtige"):
right = right + int(form["Richtige"].value)
if form.has_key("Eingabe"):
#if "Eingabe" in form: #funktioniert auch so :D
if form["Eingabe"].value==form["Ergebnis"].value:
right = right +1
print "Content-Type: text/html\n"
print "<html>"
print "<body>"
print "<head><title>Kopfrechner</title></head>"
if z <=6:
print "%i %s %i" % (x, o, y)
print "<form action='kopfrechner.cgi' method='POST'>"
print "Ihre Loesung:<br><input name='Eingabe' type='text' size='10' maxlength='4'/>"
print "<input type='submit' value='Senden' />"
print "<input type='hidden' name='ErsteZahl' value='%i'>" % x
print "<input type='hidden' name='ZweiteZahl' value='%i'>" % y
print "<input type='hidden' name='Zaehler' value=",z,">"
print "<input type='hidden' name='Ergebnis' value='%i'>" %erg
print "<input type='hidden' name='Richtige' value='%i'>" %right
print "</form>"
else:
print "Sie haben %i von %i Aufgaben richtig geloest." % (right, z-1)
print "</body>"
print "</html>"
| [
[
1,
0,
0.0508,
0.0169,
0,
0.66,
0,
934,
0,
1,
0,
0,
934,
0,
0
],
[
1,
0,
0.0678,
0.0169,
0,
0.66,
0.0476,
691,
0,
1,
0,
0,
691,
0,
0
],
[
1,
0,
0.0847,
0.0169,
0,
... | [
"import cgi",
"import cgitb",
"import random",
"cgitb.enable()",
"form = cgi.FieldStorage()",
"x = random.randint(1, 10)",
"y = random.randint(1, 10)",
"z = 0",
"erg = 0",
"right = 0",
"if form.has_key(\"Zaehler\"):\n z = z + int(form[\"Zaehler\"].value)",
" z = z + int(form[\"Zaehler\"]... |
#!/usr/bin/python
import cgi
import cgitb
cgitb.enable()
print "Content-Type: text/html\n"
print "<html>"
print "<body>"
for a in range(1,21):
print str(a**2)+'<br/>'
print "</body>"
print "</html>"
| [
[
1,
0,
0.1765,
0.0588,
0,
0.66,
0,
934,
0,
1,
0,
0,
934,
0,
0
],
[
1,
0,
0.2353,
0.0588,
0,
0.66,
0.125,
691,
0,
1,
0,
0,
691,
0,
0
],
[
8,
0,
0.2941,
0.0588,
0,
0... | [
"import cgi",
"import cgitb",
"cgitb.enable()",
"print(\"Content-Type: text/html\\n\")",
"print(\"<html>\")",
"print(\"<body>\")",
"for a in range(1,21):\n print(str(a**2)+'<br/>')",
" print(str(a**2)+'<br/>')",
"print(\"</body>\")",
"print(\"</html>\")"
] |
#!/usr/bin/python
import cgi
import cgitb
cgitb.enable()
print "Content-Type: text/html\n"
print "<html>"
print "<head><title>Hallo Tim</title></head>"
print "<body>"
print "Hallo Welt!"
print "</body>"
print "</html>" | [
[
1,
0,
0.2143,
0.0714,
0,
0.66,
0,
934,
0,
1,
0,
0,
934,
0,
0
],
[
1,
0,
0.2857,
0.0714,
0,
0.66,
0.1111,
691,
0,
1,
0,
0,
691,
0,
0
],
[
8,
0,
0.3571,
0.0714,
0,
... | [
"import cgi",
"import cgitb",
"cgitb.enable()",
"print(\"Content-Type: text/html\\n\")",
"print(\"<html>\")",
"print(\"<head><title>Hallo Tim</title></head>\")",
"print(\"<body>\")",
"print(\"Hallo Welt!\")",
"print(\"</body>\")",
"print(\"</html>\")"
] |
#!/usr/bin/python
#-*-coding: utf-8-*-
import os
import sys
import random
import string
def getRandomQuote():
files=os.listdir("/usr/share/games/fortune")
files=[f for f in files if ".dat" not in f and ".u8" not in f]
f=random.sample(files, 1)
s=file("/usr/share/games/fortune/"+f[0]).read()
quotes=s.split("\n%\n")
return (random.sample(quotes, 1))[0]
def getQuote(pat):
files=os.listdir("/usr/share/games/fortune")
files=[f for f in files if ".dat" not in f and ".u8" not in f]
random.shuffle(files)
for f in files:
s=file("/usr/share/games/fortune/"+f).read()
quotes=s.split("\n%\n")
for q in quotes:
if pat in q:
return q
return None
if __name__=="__main__":
if len(sys.argv)>1 and sys.argv[1]=="-m":
quote=getQuote(sys.argv[2])
else:
quote=getRandomQuote()
print quote
| [
[
1,
0,
0.0952,
0.0238,
0,
0.66,
0,
688,
0,
1,
0,
0,
688,
0,
0
],
[
1,
0,
0.119,
0.0238,
0,
0.66,
0.1667,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.1429,
0.0238,
0,
0... | [
"import os",
"import sys",
"import random",
"import string",
"def getRandomQuote():\n files=os.listdir(\"/usr/share/games/fortune\")\n files=[f for f in files if \".dat\" not in f and \".u8\" not in f]\n f=random.sample(files, 1)\n s=file(\"/usr/share/games/fortune/\"+f[0]).read()\n quotes=s.... |
#!/usr/bin/python
import os
import cgi
import cgitb
cgitb.enable()
print "Content-Type: text/html\n"
print "<html>"
print "<head><title>Hallo Tim</title></head>"
print "<body>"
if os.environ["HTTP_ACCEPT_LANGUAGE"][:2]=='en':
print "Hello World!"
else:
print "Hallo Welt!"
print "</body>"
print "</html>"
| [
[
1,
0,
0.1667,
0.0556,
0,
0.66,
0,
688,
0,
1,
0,
0,
688,
0,
0
],
[
1,
0,
0.2222,
0.0556,
0,
0.66,
0.1,
934,
0,
1,
0,
0,
934,
0,
0
],
[
1,
0,
0.2778,
0.0556,
0,
0.6... | [
"import os",
"import cgi",
"import cgitb",
"cgitb.enable()",
"print(\"Content-Type: text/html\\n\")",
"print(\"<html>\")",
"print(\"<head><title>Hallo Tim</title></head>\")",
"print(\"<body>\")",
"if os.environ[\"HTTP_ACCEPT_LANGUAGE\"][:2]=='en': \n print(\"Hello World!\")\nelse:... |
#!/usr/bin/python
import os
print "Content-Type: text/html\n"
for key in os.environ:
print key, "="
print os.environ[key], "<br />" | [
[
1,
0,
0.4286,
0.1429,
0,
0.66,
0,
688,
0,
1,
0,
0,
688,
0,
0
],
[
8,
0,
0.5714,
0.1429,
0,
0.66,
0.5,
535,
3,
1,
0,
0,
0,
0,
1
],
[
6,
0,
0.8571,
0.4286,
0,
0.66,... | [
"import os",
"print(\"Content-Type: text/html\\n\")",
"for key in os.environ:\n print(key, \"=\")\n print(os.environ[key], \"<br />\")",
" print(key, \"=\")",
" print(os.environ[key], \"<br />\")"
] |
#!/usr/bin/python
#-*-coding: utf-8-*-
import os
import sys
import random
import string
def getRandomQuote():
files=os.listdir("/usr/share/games/fortune")
files=[f for f in files if ".dat" not in f and ".u8" not in f]
f=random.sample(files, 1)
s=file("/usr/share/games/fortune/"+f[0]).read()
quotes=s.split("\n%\n")
return (random.sample(quotes, 1))[0]
def getQuote(pat):
files=os.listdir("/usr/share/games/fortune")
files=[f for f in files if ".dat" not in f and ".u8" not in f]
random.shuffle(files)
for f in files:
s=file("/usr/share/games/fortune/"+f).read()
quotes=s.split("\n%\n")
for q in quotes:
if pat in q:
return q
return None
if __name__=="__main__":
if len(sys.argv)>1 and sys.argv[1]=="-m":
quote=getQuote(sys.argv[2])
else:
quote=getRandomQuote()
print quote
| [
[
1,
0,
0.0952,
0.0238,
0,
0.66,
0,
688,
0,
1,
0,
0,
688,
0,
0
],
[
1,
0,
0.119,
0.0238,
0,
0.66,
0.1667,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.1429,
0.0238,
0,
0... | [
"import os",
"import sys",
"import random",
"import string",
"def getRandomQuote():\n files=os.listdir(\"/usr/share/games/fortune\")\n files=[f for f in files if \".dat\" not in f and \".u8\" not in f]\n f=random.sample(files, 1)\n s=file(\"/usr/share/games/fortune/\"+f[0]).read()\n quotes=s.... |
#!/usr/bin/python
import cgi
import cgitb
cgitb.enable()
print "Content-Type: text/html\n"
print "<html>"
print "<body>"
form = cgi.FieldStorage()
if form.has_key("n"):
n = form.getvalue("n")
for a in range(1,int(n)+1):
print str(a**2)+'<br/>'
else:
n = 21
for a in range(1,n):
print str(a**2)+'<br/>'
print "</body>"
print "</html>"
| [
[
1,
0,
0.1071,
0.0357,
0,
0.66,
0,
934,
0,
1,
0,
0,
934,
0,
0
],
[
1,
0,
0.1429,
0.0357,
0,
0.66,
0.1111,
691,
0,
1,
0,
0,
691,
0,
0
],
[
8,
0,
0.1786,
0.0357,
0,
... | [
"import cgi",
"import cgitb",
"cgitb.enable()",
"print(\"Content-Type: text/html\\n\")",
"print(\"<html>\")",
"print(\"<body>\")",
"form = cgi.FieldStorage()",
"if form.has_key(\"n\"):\n\n n = form.getvalue(\"n\")\n \n for a in range(1,int(n)+1):\n print(str(a**2)+'<br/>')\n\nelse:... |
#!/usr/bin/python
import cgi
import cgitb
cgitb.enable()
print "Content-Type: text/html\n"
print "<html>"
print "<head><title>Hallo Tim</title></head>"
print "<body>"
print "Hallo Welt!"
print "</body>"
print "</html>" | [
[
1,
0,
0.2143,
0.0714,
0,
0.66,
0,
934,
0,
1,
0,
0,
934,
0,
0
],
[
1,
0,
0.2857,
0.0714,
0,
0.66,
0.1111,
691,
0,
1,
0,
0,
691,
0,
0
],
[
8,
0,
0.3571,
0.0714,
0,
... | [
"import cgi",
"import cgitb",
"cgitb.enable()",
"print(\"Content-Type: text/html\\n\")",
"print(\"<html>\")",
"print(\"<head><title>Hallo Tim</title></head>\")",
"print(\"<body>\")",
"print(\"Hallo Welt!\")",
"print(\"</body>\")",
"print(\"</html>\")"
] |
#!/usr/bin/python
import cgi
import cgitb
import fortune
cgitb.enable()
print "Content-Type: text/html\n"
print "<html>"
print "<body>"
print "<head><title>Fortune</title></head>"
form = cgi.FieldStorage()
if form.has_key("m"):
#m = form["m"].value //alternative
m = form.getvalue("m")
print fortune.getQuote(m)
else:
m=""
print fortune.getRandomQuote()
print "<form action='fortune.cgi'>"
print "In Zitat enthalten: <br>\n"
print "<input name='m' type='text' size='30' maxlength='30' value=",m,">"
print "<input type='Submit' value='Ok'>"
print "</form>"
print "</body>"
print "</html>"
| [
[
1,
0,
0.0938,
0.0312,
0,
0.66,
0,
934,
0,
1,
0,
0,
934,
0,
0
],
[
1,
0,
0.125,
0.0312,
0,
0.66,
0.0625,
691,
0,
1,
0,
0,
691,
0,
0
],
[
1,
0,
0.1562,
0.0312,
0,
0... | [
"import cgi",
"import cgitb",
"import fortune",
"cgitb.enable()",
"print(\"Content-Type: text/html\\n\")",
"print(\"<html>\")",
"print(\"<body>\")",
"print(\"<head><title>Fortune</title></head>\")",
"form = cgi.FieldStorage()",
"if form.has_key(\"m\"):\n #m = form[\"m\"].value //alternative\n ... |
#!/usr/bin/python
import cgi
import cgitb
cgitb.enable()
print "Content-Type: text/html\n"
print "<html>"
print "<head>"
print "<title> ptreb quad cgi </title>"
print "</head>"
print "<body>"
print [x**2 for x in range(1,21)]
print "</body>"
print "</html>"
| [
[
1,
0,
0.1875,
0.0625,
0,
0.66,
0,
934,
0,
1,
0,
0,
934,
0,
0
],
[
1,
0,
0.25,
0.0625,
0,
0.66,
0.0909,
691,
0,
1,
0,
0,
691,
0,
0
],
[
8,
0,
0.3125,
0.0625,
0,
0.... | [
"import cgi",
"import cgitb",
"cgitb.enable()",
"print(\"Content-Type: text/html\\n\")",
"print(\"<html>\")",
"print(\"<head>\")",
"print(\"<title> ptreb quad cgi </title>\")",
"print(\"</head>\")",
"print(\"<body>\")",
"print([x**2 for x in range(1,21)])",
"print(\"</body>\")",
"print(\"</htm... |
#!/usr/bin/python
print "Content-Type: text/html\n"
import cgi
import cgitb
cgitb.enable()
import os
template = "<html><head><title>%s</title></head><body>%s</body></html>"
title = "Mein Titel"
content = "<h2>Hallo international</h2>"
dic = {"de":"hallo welt", "en":"hello World"}
mylan = "de"
lan = os.environ["HTTP_ACCEPT_LANGUAGE"]
if lan[:2] == "en":
mylan = "en"
content += "<p>" + dic[mylan] + "</p>"
print template % (title, content)
| [
[
8,
0,
0.0909,
0.0455,
0,
0.66,
0,
535,
3,
1,
0,
0,
0,
0,
1
],
[
1,
0,
0.1818,
0.0455,
0,
0.66,
0.0833,
934,
0,
1,
0,
0,
934,
0,
0
],
[
1,
0,
0.2273,
0.0455,
0,
0.... | [
"print(\"Content-Type: text/html\\n\")",
"import cgi",
"import cgitb",
"cgitb.enable()",
"import os",
"template = \"<html><head><title>%s</title></head><body>%s</body></html>\"",
"title = \"Mein Titel\"",
"content = \"<h2>Hallo international</h2>\"",
"dic = {\"de\":\"hallo welt\", \"en\":\"hello Wor... |
#!/usr/bin/python
#-*- coding: utf-8 -*-
# print erzeugt einen zeilunumbruch automatisch
print "Content-Type: text/html\n"
# wichtig cgi module importieren
# import ohne .py wenn im selben ordner
# fortune.methode zum benutzen einer funktion
import fortune
import cgi
import cgitb
cgitb.enable()
#main, war in fortunes.py drin
f1 = './fortunes/fortunes'
f2 = './fortunes/riddles'
f3 = './fortunes/literature'
dump = './dump.txt'
lall = []
source = list((f1,f2,f3)) # liste mit quelldateien
fortune.dumpString(fortune.getString(source), dump) # riesenstring in datei schreiben
lall = fortune.getString(source).split('\n%\n') # jedes Zitat ein Listenelement
#args = sys.argv[1:3]
#content += 'args: %s \n' % (args)
#content += printText(lall, args[1]) if len(args) >= 2 and args[0] == '-m' else printText(lall)
# alle requeststring parameter holen in form speichern
form = cgi.FieldStorage()
# m initialisieren, pattern
m = ""
# heredoc string benutzen um zeilenumbrueche im Seitenquelltext automatisch zu haben
# nicht mehr noetig \n zu setzen
template = """
<html>
<head><title>%s</title></head>
<body>\n%s</body>
</html>
"""
title = "Mein Titel"
content = "<h2>Fortunes</h2>\n"
if "m" in form:
m = form["m"].value
# benutzer darf suchwort eingeben und ok klicken
# \n um seitenquelltext lesbar zu machen
# variablen mit %s string ersetzung vormerken
content += """
<form action='fortune_ok.cgi' method='GET' >
<input type='text' name='m' size='40' maxlength='10' value='%s'><br />
<input type='submit' name='ok' value='OK' size='90' maxlength='50' ><br />
"""
content += "</form>\n"
content = content % m
# wenn m nicht gesetzt ist abfangen
if len(m) > 0:
content += fortune.printText(lall, m)
else:
content += fortune.printText(lall)
print template % (title, content)
| [
[
8,
0,
0.0694,
0.0139,
0,
0.66,
0,
535,
3,
1,
0,
0,
0,
0,
1
],
[
1,
0,
0.1389,
0.0139,
0,
0.66,
0.0476,
638,
0,
1,
0,
0,
638,
0,
0
],
[
1,
0,
0.1528,
0.0139,
0,
0.... | [
"print(\"Content-Type: text/html\\n\")",
"import fortune",
"import cgi",
"import cgitb",
"cgitb.enable()",
"f1 = './fortunes/fortunes'",
"f2 = './fortunes/riddles'",
"f3 = './fortunes/literature'",
"dump = './dump.txt'",
"lall = []",
"source = list((f1,f2,f3)) # liste mit quelldateien",
"fort... |
#!/usr/bin/python
print "Content-Type: text/html\n"
print "<html>"
print "<head>"
print "<title> ptreb hallo cgi </title>"
print "</head>"
print "<body>"
print "Hello CGI Python "
print "</body>"
print "</html>"
| [
[
8,
0,
0.25,
0.0833,
0,
0.66,
0,
535,
3,
1,
0,
0,
0,
0,
1
],
[
8,
0,
0.4167,
0.0833,
0,
0.66,
0.125,
535,
3,
1,
0,
0,
0,
0,
1
],
[
8,
0,
0.5,
0.0833,
0,
0.66,
... | [
"print(\"Content-Type: text/html\\n\")",
"print(\"<html>\")",
"print(\"<head>\")",
"print(\"<title> ptreb hallo cgi </title>\")",
"print(\"</head>\")",
"print(\"<body>\")",
"print(\"Hello CGI Python \")",
"print(\"</body>\")",
"print(\"</html>\")"
] |
#!/usr/bin/python
#-*- coding: utf-8 -*-
print "Content-Type: text/html\n"
import cgi
import cgitb
cgitb.enable()
import random
form = cgi.FieldStorage()
#zustaende auslesen
# variablen initialisieren
# aus fieldStorage komme nur strings => immer casten
title = "CGI Rechner"
runde = int(form["runde"].value) +1 if "runde" in form else 0 # vorverarbeitung hier machen
# muss richtiges ergebnis des vorigen klicks merken
prevresult = int(form["prevresult"].value) if "prevresult" in form else None
right = int(form["right"].value) if "right" in form else 0
userresult = int(form["userresult"].value) if "userresult" in form else None
result = None
z1 = random.randint(1,10)
z2 = random.randint(1,10)
operator = None
def checkresult(prevresult, userresult):
if prevresult == userresult:
return 1
return 0
def resultpage():
content = """
<h2>Ergebnis</h2><br />
Sie haben: %d von %d Aufgaben richtig gelösst!<br />
<a href='rechner.cgi'>nochmal spielen</a>
"""
return content % (right, runde)
def aufgabenpage(operator):
content = """
<p>
Berechnen Sie: %d %s %d <br />
</p>
<form action='rechner.cgi' method='GET'>
<input type='hidden' name='runde' value='%d'>
<input type='hidden' name='right' value='%d'>
<input type='hidden' name='prevresult' value='%d'>
Lösung: <input type='text' name='userresult'><br />
<input type='submit' value='OK'>
"""
# runde erhoehen
global runde
return content % (z1, operator, z2, runde, right,result)
if runde != 0:
"""ausser in 0. runde, da gibts noch kein userinput"""
global right
right += checkresult(prevresult, userresult)
if runde < 3:
"""additionsaufgabe"""
result = z1 + z2
operator = "+"
content = aufgabenpage(operator)
elif runde < 6:
"""multiplikationsaufgabe"""
result = z1 * z2
operator = "*"
content = aufgabenpage(operator)
if runde >= 6:
content = resultpage()
tmpl = """
<html>
<head><title>%s</title></head>
<body>%s</body>
</html>
"""
# ausgabe
print tmpl % (title, content)
| [
[
8,
0,
0.0455,
0.0114,
0,
0.66,
0,
535,
3,
1,
0,
0,
0,
0,
1
],
[
1,
0,
0.0682,
0.0114,
0,
0.66,
0.0455,
934,
0,
1,
0,
0,
934,
0,
0
],
[
1,
0,
0.0795,
0.0114,
0,
0.... | [
"print(\"Content-Type: text/html\\n\")",
"import cgi",
"import cgitb",
"cgitb.enable()",
"import random",
"form = cgi.FieldStorage()",
"title = \"CGI Rechner\"",
"runde = int(form[\"runde\"].value) +1 if \"runde\" in form else 0 # vorverarbeitung hier machen",
"prevresult = int(form[\"prevresult\"].... |
#!/usr/bin/python
print "Content-Type: text/html\n"
import cgi
import cgitb
import os
cgitb.enable()
print "<html>"
print "<head>"
print "<title> ptreb quadn cgi </title>"
print "</head>"
print "<body>"
form = cgi.FieldStorage() # inhalt query string
n = 20
if "n" in form:
n = int(form["n"].value)
print [z**2 for z in range(1,n)]
print n
print "</body>"
print "</html>" | [
[
8,
0,
0.0833,
0.0417,
0,
0.66,
0,
535,
3,
1,
0,
0,
0,
0,
1
],
[
1,
0,
0.125,
0.0417,
0,
0.66,
0.0625,
934,
0,
1,
0,
0,
934,
0,
0
],
[
1,
0,
0.1667,
0.0417,
0,
0.6... | [
"print(\"Content-Type: text/html\\n\")",
"import cgi",
"import cgitb",
"import os",
"cgitb.enable()",
"print(\"<html>\")",
"print(\"<head>\")",
"print(\"<title> ptreb quadn cgi </title>\")",
"print(\"</head>\")",
"print(\"<body>\")",
"form = cgi.FieldStorage() # inhalt query string",
"n = 20",... |
#!/usr/bin/python
#-*- coding: utf-8 -*-
# alles in einem nicht modul ausgelagert
print "Content-Type: text/html\n"
# wichtig cgi module importieren
import cgi
import cgitb
cgitb.enable()
import os
import random
import string
import sys
def getString(source):
"""Gibt einen grossen String zurueck und erwartet eine Liste von
Dateinamen.
"""
collection = ''
for f in source:
file_obj = file(f, 'r') # dateiobjekt
collection += '\n%\n'+ file_obj.read()
return collection # automatisch schliessen hoffentlich
def dumpString(string, filename):
"""Schreibt den uebergebenen string in die Datei filename.
"""
handle = file(filename, 'w')
handle.write(string)
def printText(collection # liste mit Zitaten (list)
, p=None # gesuchtes pattern (String)
):
"""Liefert ein total zufaelliges oder Zitat oder ein zfaelliges, welches das Pattern enthaelt.
"""
if p is None:
return random.choice(lall)
lfilter = [text for text in collection if p in text] # listcomprehension
# wenn lfilter eine leere liste ist wurde das pattern nicht gefunden
#random.choice(seq) liefert ein zufaelliges element einer sequenz
return random.choice(lfilter) if lfilter else 'Leider kommt dieser Ausdruck niemals vor'
#main
f1 = './fortunes/fortunes'
f2 = './fortunes/riddles'
f3 = './fortunes/literature'
dump = './dump.txt'
lall = []
source = list((f1,f2,f3)) # liste mit quelldateien
dumpString(getString(source), dump) # riesenstring in datei schreiben
lall = getString(source).split('\n%\n') # jedes Zitat ein Listenelement
#args = sys.argv[1:3]
#content += 'args: %s \n' % (args)
#content += printText(lall, args[1]) if len(args) >= 2 and args[0] == '-m' else printText(lall)
# alle requeststring parameter holen in form speichern
form = cgi.FieldStorage()
# m initialisieren, pattern
m = ""
# heredoc string benutzen um zeilenumbrueche im Seitenquelltext automatisch zu haben
# nicht mehr noetig \n zu setzen
template = """
<html>
<head><title>%s</title></head>
<body>\n%s</body>
</html>
"""
title = "Mein Titel"
content = "<h2>Fortunes</h2>\n"
if "m" in form:
m = form["m"].value
# benutzer darf suchwort eingeben und ok klicken
# \n um seitenquelltext lesbar zu machen
# variablen mit %s string ersetzung vormerken
content += """
<form action='fortune.cgi' method='GET' >
<input type='text' name='m' size='40' maxlength='10' value='%s'><br />
<input type='submit' name='ok' value='OK' size='90' maxlength='50' ><br />
"""
content += "</form>\n"
content = content % m
# wenn m nicht gesetzt ist abfangen
if len(m) > 0:
content += printText(lall, m)
else:
content += printText(lall)
print template % (title, content)
| [
[
8,
0,
0.0495,
0.0099,
0,
0.66,
0,
535,
3,
1,
0,
0,
0,
0,
1
],
[
1,
0,
0.0792,
0.0099,
0,
0.66,
0.037,
934,
0,
1,
0,
0,
934,
0,
0
],
[
1,
0,
0.0891,
0.0099,
0,
0.6... | [
"print(\"Content-Type: text/html\\n\")",
"import cgi",
"import cgitb",
"cgitb.enable()",
"import os",
"import random",
"import string",
"import sys",
"def getString(source):\n \"\"\"Gibt einen grossen String zurueck und erwartet eine Liste von\n Dateinamen.\n \"\"\"\n collection = ''\n ... |
#!/usr/bin/python
import cgi
import cgitb
cgitb.enable()
print "Content-Type: text/html\n"
print "<html>"
print "<head>"
print "<title> ptreb quad cgi </title>"
print "</head>"
print "<body>"
print [x**2 for x in range(1,21)]
print "</body>"
print "</html>"
| [
[
1,
0,
0.1875,
0.0625,
0,
0.66,
0,
934,
0,
1,
0,
0,
934,
0,
0
],
[
1,
0,
0.25,
0.0625,
0,
0.66,
0.0909,
691,
0,
1,
0,
0,
691,
0,
0
],
[
8,
0,
0.3125,
0.0625,
0,
0.... | [
"import cgi",
"import cgitb",
"cgitb.enable()",
"print(\"Content-Type: text/html\\n\")",
"print(\"<html>\")",
"print(\"<head>\")",
"print(\"<title> ptreb quad cgi </title>\")",
"print(\"</head>\")",
"print(\"<body>\")",
"print([x**2 for x in range(1,21)])",
"print(\"</body>\")",
"print(\"</htm... |
#!/usr/bin/python
#-*- coding: utf-8 -*-
# modul das nur die logik funktionen enthaelt, webanwendung und darstellung in
# cgi script
import os
import random
import string
import sys
def getString(source):
"""Gibt einen grossen String zurueck und erwartet eine Liste von
Dateinamen.
"""
collection = ''
for f in source:
file_obj = file(f, 'r') # dateiobjekt
collection += '\n%\n'+ file_obj.read()
return collection # automatisch schliessen hoffentlich
def dumpString(string, filename):
"""Schreibt den uebergebenen string in die Datei filename.
"""
handle = file(filename, 'w')
handle.write(string)
def printText(collection # liste mit Zitaten (list)
, p=None # gesuchtes pattern (String)
):
"""Liefert ein total zufaelliges oder Zitat oder ein zfaelliges, welches das Pattern enthaelt.
"""
if p is None:
return random.choice(lall)
lfilter = [text for text in collection if p in text] # listcomprehension
# wenn lfilter eine leere liste ist wurde das pattern nicht gefunden
#random.choice(seq) liefert ein zufaelliges element einer sequenz
return random.choice(lfilter) if lfilter else 'Leider kommt dieser Ausdruck niemals vor'
| [
[
1,
0,
0.15,
0.025,
0,
0.66,
0,
688,
0,
1,
0,
0,
688,
0,
0
],
[
1,
0,
0.175,
0.025,
0,
0.66,
0.1667,
715,
0,
1,
0,
0,
715,
0,
0
],
[
1,
0,
0.2,
0.025,
0,
0.66,
... | [
"import os",
"import random",
"import string",
"import sys",
"def getString(source):\n \"\"\"Gibt einen grossen String zurueck und erwartet eine Liste von\n Dateinamen.\n \"\"\"\n collection = ''\n for f in source:\n file_obj = file(f, 'r') # dateiobjekt\n collection += '\\n%\\n... |
#!/usr/bin/python
print "Content-Type: text/html\n"
import cgi
import cgitb
cgitb.enable()
import os
template = "<html><head><title>%s</title></head><body>%s</body></html>"
title = "Mein Titel"
content = "<h2>Hallo international</h2>"
dic = {"de":"hallo welt", "en":"hello World"}
mylan = "de"
lan = os.environ["HTTP_ACCEPT_LANGUAGE"]
if lan[:2] == "en":
mylan = "en"
content += "<p>" + dic[mylan] + "</p>"
print template % (title, content)
| [
[
8,
0,
0.0909,
0.0455,
0,
0.66,
0,
535,
3,
1,
0,
0,
0,
0,
1
],
[
1,
0,
0.1818,
0.0455,
0,
0.66,
0.0833,
934,
0,
1,
0,
0,
934,
0,
0
],
[
1,
0,
0.2273,
0.0455,
0,
0.... | [
"print(\"Content-Type: text/html\\n\")",
"import cgi",
"import cgitb",
"cgitb.enable()",
"import os",
"template = \"<html><head><title>%s</title></head><body>%s</body></html>\"",
"title = \"Mein Titel\"",
"content = \"<h2>Hallo international</h2>\"",
"dic = {\"de\":\"hallo welt\", \"en\":\"hello Wor... |
#!/usr/bin/python
#-*- coding: utf-8 -*-
# modul das nur die logik funktionen enthaelt, webanwendung und darstellung in
# cgi script
import os
import random
import string
import sys
def getString(source):
"""Gibt einen grossen String zurueck und erwartet eine Liste von
Dateinamen.
"""
collection = ''
for f in source:
file_obj = file(f, 'r') # dateiobjekt
collection += '\n%\n'+ file_obj.read()
return collection # automatisch schliessen hoffentlich
def dumpString(string, filename):
"""Schreibt den uebergebenen string in die Datei filename.
"""
handle = file(filename, 'w')
handle.write(string)
def printText(collection # liste mit Zitaten (list)
, p=None # gesuchtes pattern (String)
):
"""Liefert ein total zufaelliges oder Zitat oder ein zfaelliges, welches das Pattern enthaelt.
"""
if p is None:
return random.choice(lall)
lfilter = [text for text in collection if p in text] # listcomprehension
# wenn lfilter eine leere liste ist wurde das pattern nicht gefunden
#random.choice(seq) liefert ein zufaelliges element einer sequenz
return random.choice(lfilter) if lfilter else 'Leider kommt dieser Ausdruck niemals vor'
| [
[
1,
0,
0.15,
0.025,
0,
0.66,
0,
688,
0,
1,
0,
0,
688,
0,
0
],
[
1,
0,
0.175,
0.025,
0,
0.66,
0.1667,
715,
0,
1,
0,
0,
715,
0,
0
],
[
1,
0,
0.2,
0.025,
0,
0.66,
... | [
"import os",
"import random",
"import string",
"import sys",
"def getString(source):\n \"\"\"Gibt einen grossen String zurueck und erwartet eine Liste von\n Dateinamen.\n \"\"\"\n collection = ''\n for f in source:\n file_obj = file(f, 'r') # dateiobjekt\n collection += '\\n%\\n... |
#!/usr/bin/python
print "Content-Type: text/html\n"
import cgi
import cgitb
import os
cgitb.enable()
print "<html>"
print "<head>"
print "<title> ptreb quadn cgi </title>"
print "</head>"
print "<body>"
form = cgi.FieldStorage() # inhalt query string
n = 20
if "n" in form:
n = int(form["n"].value)
print [z**2 for z in range(1,n)]
print n
print "</body>"
print "</html>" | [
[
8,
0,
0.0833,
0.0417,
0,
0.66,
0,
535,
3,
1,
0,
0,
0,
0,
1
],
[
1,
0,
0.125,
0.0417,
0,
0.66,
0.0625,
934,
0,
1,
0,
0,
934,
0,
0
],
[
1,
0,
0.1667,
0.0417,
0,
0.6... | [
"print(\"Content-Type: text/html\\n\")",
"import cgi",
"import cgitb",
"import os",
"cgitb.enable()",
"print(\"<html>\")",
"print(\"<head>\")",
"print(\"<title> ptreb quadn cgi </title>\")",
"print(\"</head>\")",
"print(\"<body>\")",
"form = cgi.FieldStorage() # inhalt query string",
"n = 20",... |
#!/usr/bin/python
#-*- coding: utf-8 -*-
# alles in einem nicht modul ausgelagert
print "Content-Type: text/html\n"
# wichtig cgi module importieren
import cgi
import cgitb
cgitb.enable()
import os
import random
import string
import sys
def getString(source):
"""Gibt einen grossen String zurueck und erwartet eine Liste von
Dateinamen.
"""
collection = ''
for f in source:
file_obj = file(f, 'r') # dateiobjekt
collection += '\n%\n'+ file_obj.read()
return collection # automatisch schliessen hoffentlich
def dumpString(string, filename):
"""Schreibt den uebergebenen string in die Datei filename.
"""
handle = file(filename, 'w')
handle.write(string)
def printText(collection # liste mit Zitaten (list)
, p=None # gesuchtes pattern (String)
):
"""Liefert ein total zufaelliges oder Zitat oder ein zfaelliges, welches das Pattern enthaelt.
"""
if p is None:
return random.choice(lall)
lfilter = [text for text in collection if p in text] # listcomprehension
# wenn lfilter eine leere liste ist wurde das pattern nicht gefunden
#random.choice(seq) liefert ein zufaelliges element einer sequenz
return random.choice(lfilter) if lfilter else 'Leider kommt dieser Ausdruck niemals vor'
#main
f1 = './fortunes/fortunes'
f2 = './fortunes/riddles'
f3 = './fortunes/literature'
dump = './dump.txt'
lall = []
source = list((f1,f2,f3)) # liste mit quelldateien
dumpString(getString(source), dump) # riesenstring in datei schreiben
lall = getString(source).split('\n%\n') # jedes Zitat ein Listenelement
#args = sys.argv[1:3]
#content += 'args: %s \n' % (args)
#content += printText(lall, args[1]) if len(args) >= 2 and args[0] == '-m' else printText(lall)
# alle requeststring parameter holen in form speichern
form = cgi.FieldStorage()
# m initialisieren, pattern
m = ""
# heredoc string benutzen um zeilenumbrueche im Seitenquelltext automatisch zu haben
# nicht mehr noetig \n zu setzen
template = """
<html>
<head><title>%s</title></head>
<body>\n%s</body>
</html>
"""
title = "Mein Titel"
content = "<h2>Fortunes</h2>\n"
if "m" in form:
m = form["m"].value
# benutzer darf suchwort eingeben und ok klicken
# \n um seitenquelltext lesbar zu machen
# variablen mit %s string ersetzung vormerken
content += """
<form action='fortune.cgi' method='GET' >
<input type='text' name='m' size='40' maxlength='10' value='%s'><br />
<input type='submit' name='ok' value='OK' size='90' maxlength='50' ><br />
"""
content += "</form>\n"
content = content % m
# wenn m nicht gesetzt ist abfangen
if len(m) > 0:
content += printText(lall, m)
else:
content += printText(lall)
print template % (title, content)
| [
[
8,
0,
0.0495,
0.0099,
0,
0.66,
0,
535,
3,
1,
0,
0,
0,
0,
1
],
[
1,
0,
0.0792,
0.0099,
0,
0.66,
0.037,
934,
0,
1,
0,
0,
934,
0,
0
],
[
1,
0,
0.0891,
0.0099,
0,
0.6... | [
"print(\"Content-Type: text/html\\n\")",
"import cgi",
"import cgitb",
"cgitb.enable()",
"import os",
"import random",
"import string",
"import sys",
"def getString(source):\n \"\"\"Gibt einen grossen String zurueck und erwartet eine Liste von\n Dateinamen.\n \"\"\"\n collection = ''\n ... |
#!/usr/bin/python
#-*- coding: utf-8 -*-
print "Content-Type: text/html\n"
import cgi
import cgitb
cgitb.enable()
import random
form = cgi.FieldStorage()
#zustaende auslesen
# variablen initialisieren
# aus fieldStorage komme nur strings => immer casten
title = "CGI Rechner"
runde = int(form["runde"].value) +1 if "runde" in form else 0 # vorverarbeitung hier machen
# muss richtiges ergebnis des vorigen klicks merken
prevresult = int(form["prevresult"].value) if "prevresult" in form else None
right = int(form["right"].value) if "right" in form else 0
userresult = int(form["userresult"].value) if "userresult" in form else None
result = None
z1 = random.randint(1,10)
z2 = random.randint(1,10)
operator = None
def checkresult(prevresult, userresult):
if prevresult == userresult:
return 1
return 0
def resultpage():
content = """
<h2>Ergebnis</h2><br />
Sie haben: %d von %d Aufgaben richtig gelösst!<br />
<a href='rechner.cgi'>nochmal spielen</a>
"""
return content % (right, runde)
def aufgabenpage(operator):
content = """
<p>
Berechnen Sie: %d %s %d <br />
</p>
<form action='rechner.cgi' method='GET'>
<input type='hidden' name='runde' value='%d'>
<input type='hidden' name='right' value='%d'>
<input type='hidden' name='prevresult' value='%d'>
Lösung: <input type='text' name='userresult'><br />
<input type='submit' value='OK'>
"""
# runde erhoehen
global runde
return content % (z1, operator, z2, runde, right,result)
if runde != 0:
"""ausser in 0. runde, da gibts noch kein userinput"""
global right
right += checkresult(prevresult, userresult)
if runde < 3:
"""additionsaufgabe"""
result = z1 + z2
operator = "+"
content = aufgabenpage(operator)
elif runde < 6:
"""multiplikationsaufgabe"""
result = z1 * z2
operator = "*"
content = aufgabenpage(operator)
if runde >= 6:
content = resultpage()
tmpl = """
<html>
<head><title>%s</title></head>
<body>%s</body>
</html>
"""
# ausgabe
print tmpl % (title, content)
| [
[
8,
0,
0.0455,
0.0114,
0,
0.66,
0,
535,
3,
1,
0,
0,
0,
0,
1
],
[
1,
0,
0.0682,
0.0114,
0,
0.66,
0.0455,
934,
0,
1,
0,
0,
934,
0,
0
],
[
1,
0,
0.0795,
0.0114,
0,
0.... | [
"print(\"Content-Type: text/html\\n\")",
"import cgi",
"import cgitb",
"cgitb.enable()",
"import random",
"form = cgi.FieldStorage()",
"title = \"CGI Rechner\"",
"runde = int(form[\"runde\"].value) +1 if \"runde\" in form else 0 # vorverarbeitung hier machen",
"prevresult = int(form[\"prevresult\"].... |
#!/usr/bin/python
print "Content-Type: text/html\n"
print "<html>"
print "<head>"
print "<title> ptreb hallo cgi </title>"
print "</head>"
print "<body>"
print "Hello CGI Python "
print "</body>"
print "</html>"
| [
[
8,
0,
0.25,
0.0833,
0,
0.66,
0,
535,
3,
1,
0,
0,
0,
0,
1
],
[
8,
0,
0.4167,
0.0833,
0,
0.66,
0.125,
535,
3,
1,
0,
0,
0,
0,
1
],
[
8,
0,
0.5,
0.0833,
0,
0.66,
... | [
"print(\"Content-Type: text/html\\n\")",
"print(\"<html>\")",
"print(\"<head>\")",
"print(\"<title> ptreb hallo cgi </title>\")",
"print(\"</head>\")",
"print(\"<body>\")",
"print(\"Hello CGI Python \")",
"print(\"</body>\")",
"print(\"</html>\")"
] |
#!/usr/bin/python
#-*- coding: utf-8 -*-
# print erzeugt einen zeilunumbruch automatisch
print "Content-Type: text/html\n"
# wichtig cgi module importieren
# import ohne .py wenn im selben ordner
# fortune.methode zum benutzen einer funktion
import fortune
import cgi
import cgitb
cgitb.enable()
#main, war in fortunes.py drin
f1 = './fortunes/fortunes'
f2 = './fortunes/riddles'
f3 = './fortunes/literature'
dump = './dump.txt'
lall = []
source = list((f1,f2,f3)) # liste mit quelldateien
fortune.dumpString(fortune.getString(source), dump) # riesenstring in datei schreiben
lall = fortune.getString(source).split('\n%\n') # jedes Zitat ein Listenelement
#args = sys.argv[1:3]
#content += 'args: %s \n' % (args)
#content += printText(lall, args[1]) if len(args) >= 2 and args[0] == '-m' else printText(lall)
# alle requeststring parameter holen in form speichern
form = cgi.FieldStorage()
# m initialisieren, pattern
m = ""
# heredoc string benutzen um zeilenumbrueche im Seitenquelltext automatisch zu haben
# nicht mehr noetig \n zu setzen
template = """
<html>
<head><title>%s</title></head>
<body>\n%s</body>
</html>
"""
title = "Mein Titel"
content = "<h2>Fortunes</h2>\n"
if "m" in form:
m = form["m"].value
# benutzer darf suchwort eingeben und ok klicken
# \n um seitenquelltext lesbar zu machen
# variablen mit %s string ersetzung vormerken
content += """
<form action='fortune_ok.cgi' method='GET' >
<input type='text' name='m' size='40' maxlength='10' value='%s'><br />
<input type='submit' name='ok' value='OK' size='90' maxlength='50' ><br />
"""
content += "</form>\n"
content = content % m
# wenn m nicht gesetzt ist abfangen
if len(m) > 0:
content += fortune.printText(lall, m)
else:
content += fortune.printText(lall)
print template % (title, content)
| [
[
8,
0,
0.0694,
0.0139,
0,
0.66,
0,
535,
3,
1,
0,
0,
0,
0,
1
],
[
1,
0,
0.1389,
0.0139,
0,
0.66,
0.0476,
638,
0,
1,
0,
0,
638,
0,
0
],
[
1,
0,
0.1528,
0.0139,
0,
0.... | [
"print(\"Content-Type: text/html\\n\")",
"import fortune",
"import cgi",
"import cgitb",
"cgitb.enable()",
"f1 = './fortunes/fortunes'",
"f2 = './fortunes/riddles'",
"f3 = './fortunes/literature'",
"dump = './dump.txt'",
"lall = []",
"source = list((f1,f2,f3)) # liste mit quelldateien",
"fort... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# setup.py
# Part of 21obuys, a package providing enumerated types for Python.
#
# Copyright © 2007 Ben Finney
# This is free software; you may copy, modify and/or distribute this work
# under the terms of the GNU General Public License, version 2 or later
# or, at your option, the terms of the Python license.
import ez_setup
ez_setup.use_setuptools()
from setuptools import setup, find_packages
setup(
name = "bigo55",
version = '1.0',
packages = find_packages('src'), # include all packages under src
package_dir = {'':'src'}, # tell distutils packages are under src
py_modules = ['captcha_price','choiceproxy','crawlerhttp','logfacade','pageparser','PersistentQueue','spider'],
# setuptools metadata
zip_safe = True,
#test_suite = "test.test_enum.suite",
package_data = {
'': ["*.*"],
},
# Project uses reStructuredText, so ensure that the docutils get
# installed or upgraded on the target machine
install_requires = ['chardet','enum','BeautifulSoup','threadpool'],
# PyPI metadata
# metadata for upload to PyPI
author = "zhongfeng",
author_email = "fzhong@travelsky.com",
description = "21obuys Package",
license = "PSF",
keywords = "360buy newegg crawlers",
classifiers = [
"Development Status :: 4 - Beta",
"License :: OSI Approved :: GNU General Public License (GPL)",
"License :: OSI Approved :: Python Software Foundation License",
"Programming Language :: Python",
"Topic :: Software Development :: Libraries :: Python Modules",
"Operating System :: OS Independent",
"Intended Audience :: Developers",
],
)
| [
[
1,
0,
0.22,
0.02,
0,
0.66,
0,
650,
0,
1,
0,
0,
650,
0,
0
],
[
8,
0,
0.24,
0.02,
0,
0.66,
0.3333,
479,
3,
0,
0,
0,
0,
0,
1
],
[
1,
0,
0.28,
0.02,
0,
0.66,
0.66... | [
"import ez_setup",
"ez_setup.use_setuptools()",
"from setuptools import setup, find_packages",
"setup(\n name = \"bigo55\",\n version = '1.0',\n packages = find_packages('src'), # include all packages under src\n package_dir = {'':'src'}, # tell distutils packages are under src\n py_modules ... |
"""
1. Generate ie6 module with win32/com/tools/readtlb.py from the ctypes
package
(I forget the details, but you can probably skip this and just use
ie6_gen.py that comes with ctypes in the samples directory -- change
the 'import ie6' below as appropriate.)
2. Generate a GUID and cut-n-paste it as PythonBHO._reg_clsid_. To
generate a GUID using pywin32 (aka "Python for Windows Extensions"):
import pythoncom
pythoncom.CreateGUID()
3. python bho_skel.py /regserver
4. Use DebugView or similar to see the output from print statements.
5. Run IE, watch output (IIRC dispinterface_EventReceiver prints out
messages for unimplemented events).
6. Remember to write something useful ;-)
"""
import sys
import _winreg
from ctypes import *
from ctypes.com import IUnknown, PIUnknown, REFIID, GUID, STDMETHOD, HRESULT, \
COMObject
from ctypes.com.automation import IDispatch, BSTR, VARIANT, \
dispinterface, DISPMETHOD
from ctypes.com.register import Registrar
from ctypes.com.connectionpoints import dispinterface_EventReceiver, \
GetConnectionPoint
import ie6 # module generated by ctypes/com/tools/readtlb.py
# _Logger is pinched from ctypes 0.6.2
# --------------------------------------------------------------------
from ctypes import windll
kernel32 = windll.kernel32
# Hm. We cannot redirect sys.stderr/sys.stdout in the inproc case,
# If the process is Python, the user would be pissed off if we did.
class _Logger(object):
# Redirect standard output and standard error to
# win32 Debug Messages. Output can be viewed for example
# in DebugView from www.sysinternals.com
_installed = 0
_text = ""
def write(self, text):
self._text += str(text)
if "\n" in self._text:
kernel32.OutputDebugStringA(self._text)
self._text = ""
def install(cls):
if cls._installed:
return
import sys
sys.stdout = sys.stderr = cls()
cls._installed = 1
install = classmethod(install)
def isatty(self):
return 0
# --------------------------------------------------------------------
_Logger.install() # redirect stdout to win32's OutputDebugStringA()
HKLM = _winreg.HKEY_LOCAL_MACHINE
BHO_KEY = ("Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\"
"Browser Helper Objects\\")
class MyRegistrar(Registrar):
def build_table(self):
table = Registrar.build_table(self)
table.extend([(HKLM, BHO_KEY+self._reg_clsid_, "", None)])
return table
class IObjectWithSite(IUnknown):
_iid_ = GUID("{FC4801A3-2BA9-11CF-A229-00AA003D7352}")
IObjectWithSite._methods_ = IUnknown._methods_ + [
(STDMETHOD(HRESULT, "SetSite", PIUnknown)),
(STDMETHOD(HRESULT, "GetSite", POINTER(c_void_p), REFIID))]
class PythonBHO(COMObject):
_reg_clsid_ = "{693D1AC0-2D77-11D8-9B9E-FB41F7E93A45}"
_reg_progid_ = "PythonBHO"
_com_interfaces_ = [IObjectWithSite]
def _get_registrar(cls):
return MyRegistrar(cls)
_get_registrar = classmethod(_get_registrar)
def IObjectWithSite_SetSite(self, this, pUnkSite):
self.browser = POINTER(ie6.IWebBrowser2)()
hr = pUnkSite.QueryInterface(
byref(ie6.IWebBrowser2._iid_), byref(self.browser))
sink = DWebBrowserEvents2Impl()
sink.handle = sink.connect(self.browser)
class DWebBrowserEvents2Impl(dispinterface_EventReceiver):
_com_interfaces_ = [ie6.DWebBrowserEvents2]
def OnQuit(self, this, *args):
self.disconnect(self.handle)
def BeforeNavigate2(self, this, pDisp, url, Flags, TargetFrameName,
PostData, Headers, Cancel):
print "url", url
if __name__ == '__main__':
from ctypes.com.server import UseCommandLine
UseCommandLine(PythonBHO)
| [
[
8,
0,
0.1068,
0.2051,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.2222,
0.0085,
0,
0.66,
0.05,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.2308,
0.0085,
0,
0.66,
... | [
"\"\"\"\n1. Generate ie6 module with win32/com/tools/readtlb.py from the ctypes\n package\n\n (I forget the details, but you can probably skip this and just use\n ie6_gen.py that comes with ctypes in the samples directory -- change\n the 'import ie6' below as appropriate.)",
"import sys",
"import _winreg",
... |
#!/usr/bin/env python
# -*- coding: utf8 -*-
'''
Created on 2011-7-26
京东价格图片识别模块
@author: zhongfeng
'''
import ImageFilter, ImageChops
from captcha_price import *
from j360buy.j360_feature import J360buy_FEATURES_MAP__
import Image
import re
import time
try:
import psyco
psyco.full()
except ImportError:
pass
class CaptchaProfile_360Buy(CaptchaProfile):
def __init__(self,features_map = J360buy_FEATURES_MAP__):
super(CaptchaProfile_360Buy,self).__init__(features_map)
def __new__(cls,features_map = J360buy_FEATURES_MAP__):
return super(CaptchaProfile_360Buy, cls).__new__(cls,features_map)
def split(self, im,top = 3,bottom = 11):
matrix = {(48,12) : [(15, 3, 21, 11), (23, 3, 25, 11),(27,3,33,11),(35,3,41,11)],
(52,12) : [(15, 3, 21, 11), (23, 3, 29, 11),(31,3,33,11),(35,3,41,11),(43,3,49,11)],
(65,12) : [(15, 3, 21, 11), (23, 3, 29, 11),(31,3,37,11),(39,3,41,11),(43,3,49,11),(51,3,57,11)],
(75,12) : [(15, 3, 21, 11), (23, 3, 29, 11),(31,3,37,11),(39,3,45,11),(47,3,49,11),(51,3,57,11),(59, 3, 65, 11)],
(80,12) : [(15, 3, 21, 11), (23, 3, 29, 11),(31,3,37,11),(39,3,45,11),(47,3,53,11),(55,3,57,11),(59, 3, 65, 11),(67,3,73,11)]
}
return [im.crop(box) for box in matrix[im.size]]
def captcha_360buy(filename):
return captcha(filename, CaptchaProfile_360Buy())
def test():
print captcha_360buy(r'c:\gp359329,2.png')
if __name__ == '__main__':
im = Image.open(r'c:\1.png')
im2 = Image.open(r'c:\1.png')
diff = ImageChops.difference(im, im2)
im = im.filter(ImageFilter.EDGE_ENHANCE_MORE).convert('L').convert('1')
dt = im.getdata()
print im.size
it1 = im.crop((15, 3, 21, 11))
it2 = im.crop((23, 3, 29, 11))
it3 = im.crop((31, 3, 37, 11))
it4 = im.crop((39, 3, 45, 11))
it5 = im.crop((47, 3, 49, 11))
it6 = im.crop((51, 3, 57, 11))
it7 = im.crop((59, 3, 65, 11))
cia = CaptchaImageAlgorithm()
s7 = cia.GetBinaryMap(it1)
print s7
profile = CaptchaProfile_360Buy()
print '+++++++++++++++++++++++++++'
for t in range(100):
print captcha_360buy(r'c:\5.png')
| [
[
8,
0,
0.0972,
0.0972,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.1667,
0.0139,
0,
0.66,
0.0909,
739,
0,
2,
0,
0,
739,
0,
0
],
[
1,
0,
0.1806,
0.0139,
0,
0.66... | [
"'''\nCreated on 2011-7-26\n\n京东价格图片识别模块\n\n@author: zhongfeng\n'''",
"import ImageFilter, ImageChops",
"from captcha_price import *",
"from j360buy.j360_feature import J360buy_FEATURES_MAP__",
"import Image",
"import re",
"import time",
"try:\n import psyco\n psyco.full()\nexcept ImportError:\n... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.