languages_and_translators/final_lang/fort.py

736 lines
16 KiB
Python
Raw Normal View History

2019-03-21 14:52:07 -06:00
import ply.lex as lex
2019-03-21 18:38:52 -06:00
import ply.yacc as yacc
import sys
2019-04-22 14:47:49 -05:00
# Ignore unresolved import error if present.
from typeValidation import resultingType
2019-04-22 14:47:49 -05:00
# ----------------------------------------------------------------------------
# --------------------------------Globals-------------------------------------
# ----------------------------------------------------------------------------
2019-04-12 05:55:09 +00:00
2019-04-22 14:47:49 -05:00
kEqualityOperators = ['>', '<', '>=', '<=', '==', '/=', ]
resultQuadruplets = []
# The first quadruplet will be line 1, that way it will match the lines in
# the editor and will be easier to analyze.
quadrupletIndex = 1
# Auxiliary stacks.
operandsStack = []
operatorsStack = []
2019-04-11 23:46:23 +00:00
typesStack = []
jumpsStack = []
2019-04-11 23:46:23 +00:00
exitsStack = []
avail = []
for i in range(50):
avail.append('$' + str(i))
2019-03-21 18:38:52 -06:00
2019-04-04 23:05:36 +00:00
# Operations related to the table of symbols
symbols = {}
# Our variables start at direction 50, the temps take the first 50 directions.
currentIndex = 50
2019-04-04 23:05:36 +00:00
2019-04-22 14:47:49 -05:00
# ----------------------------------------------------------------------------
# ------------------------------Util methods----------------------------------
# ----------------------------------------------------------------------------
2019-04-12 05:55:09 +00:00
# Adds a symbol to the symbols table.
2019-04-22 14:47:49 -05:00
def addSymbol(name, symbolType):
global currentIndex
initialValue = 0 if symbolType == 'integer' else 0.0
symbols[name] = {
2019-04-11 23:46:23 +00:00
'type': symbolType,
'value': initialValue,
'direction': currentIndex
}
currentIndex += 1
# Returns the last item of a list without deleting it.
2019-04-22 14:47:49 -05:00
def peek(list):
if (len(list) == 0):
return None
return list[len(list) - 1]
2019-04-04 23:05:36 +00:00
# Checks whether or not a an operand is a temp variable.
2019-04-22 14:47:49 -05:00
def isTemp(operand):
if type(operand) is not str:
return False
operand = int(operand[1:])
if (operand < 50):
return True
return False
2019-04-22 14:47:49 -05:00
2019-04-12 05:55:09 +00:00
def fillGoto(position, fillValue):
global resultQuadruplets
# Using position - 1 because the quadruplets start at 1 and not 0.
2019-04-22 14:47:49 -05:00
resultQuadruplets[position-1] = resultQuadruplets[position -
1].replace('_', str(fillValue))
2019-04-12 05:55:09 +00:00
return
2019-04-22 14:47:49 -05:00
# ----------------------------------------------------------------------------
# ---------------------------------LEXER--------------------------------------
# ----------------------------------------------------------------------------
2019-04-12 05:55:09 +00:00
2019-03-21 18:38:52 -06:00
tokens = [
'doubleColon',
'coma',
'openBra',
'closedBra',
'int',
'rea',
'parens',
'openParen',
'closedParen',
'string',
'plus',
'minus',
'mul',
'div',
'or',
'and',
'not',
'equals',
'doubleEquals',
'notEquals',
'less',
'more',
'lessEquals',
'moreEquals',
2019-03-21 21:09:36 -06:00
'id',
2019-03-21 21:39:07 -06:00
'program',
'end',
'read',
'print',
'if',
'then',
'else',
'elif',
'do',
'swap',
'exit',
'integer',
'real',
'subroutine',
2019-03-21 20:20:55 -06:00
]
2019-03-21 21:39:07 -06:00
reserved = {
2019-04-22 14:47:49 -05:00
'program': 'program',
'end': 'end',
'read': 'read',
'print': 'print',
'if': 'if',
'then': 'then',
'else': 'else',
'elif': 'elif',
'do': 'do',
'swap': 'swap',
'exit': 'exit',
'integer': 'integer',
'real': 'real',
'subroutine': 'subroutine',
2019-03-21 21:39:07 -06:00
}
2019-03-21 20:20:55 -06:00
2019-03-21 21:09:36 -06:00
t_doubleColon = r'::'
t_coma = r','
t_openBra = r'\['
t_closedBra = r'\]'
t_parens = r'\(\)'
t_openParen = r'\('
t_closedParen = r'\)'
2019-03-21 20:20:55 -06:00
t_plus = r'\+'
t_minus = r'-'
t_mul = r'\*'
2019-03-21 22:59:22 -06:00
t_string = r'\'[a-zA-Z0-9 \t\r\n\f()\[\]\&\!\@\#\$\%\^\-\=\+\/\,]*\''
2019-03-21 21:39:07 -06:00
t_or = r'\.or\.'
t_and = r'\.and\.'
t_not = r'\.not\.'
t_doubleEquals = r'\=\='
t_equals = r'\='
t_notEquals = r'\/\='
t_div = r'\/'
t_lessEquals = r'\<\='
t_less = r'\<'
t_moreEquals = r'\>\='
t_more = r'\>'
t_ignore = ' \t\r\n\f\v'
2019-03-21 20:20:55 -06:00
2019-04-22 14:47:49 -05:00
2019-03-21 20:20:55 -06:00
def t_rea(t):
r'\d+\.\d+'
t.value = float(t.value)
return t
2019-04-22 14:47:49 -05:00
def t_int(t):
r'\d+'
t.value = int(t.value)
return t
2019-03-21 20:20:55 -06:00
def t_id(t):
2019-03-21 21:09:36 -06:00
r'[a-zA-Z_][a-zA-Z_0-9]*'
2019-03-21 21:39:07 -06:00
if t.value in reserved:
2019-04-22 14:47:49 -05:00
t.type = reserved[t.value]
else:
2019-03-21 21:39:07 -06:00
t.type = 'id'
2019-03-21 20:20:55 -06:00
return t
2019-04-22 14:47:49 -05:00
2019-03-21 20:20:55 -06:00
def t_error(t):
print("Illegal character!")
2019-03-21 22:59:22 -06:00
print(t)
2019-03-21 20:20:55 -06:00
t.lexer.skip(1)
2019-04-22 14:47:49 -05:00
2019-03-21 20:20:55 -06:00
lexer = lex.lex()
2019-04-12 05:55:09 +00:00
2019-04-22 14:47:49 -05:00
# ----------------------------------------------------------------------------
# ---------------------------------PARSER-------------------------------------
# ----------------------------------------------------------------------------
2019-04-12 05:55:09 +00:00
2019-03-21 20:20:55 -06:00
def p_programa(p):
'''
programa : program id V F B end program
2019-04-22 14:47:49 -05:00
'''
print('+++ Valid program')
2019-03-21 20:20:55 -06:00
2019-04-22 14:47:49 -05:00
2019-03-21 20:20:55 -06:00
def p_V(p):
'''
V : V Tipo Dim doubleColon Rid
|
'''
2019-04-04 23:05:36 +00:00
# Adds all the variables for this production into the
# symbols table.
if (len(p) > 1):
for name in p[5]:
addSymbol(name, p[2])
2019-03-21 20:20:55 -06:00
def p_Rid(p):
'''
Rid : id
| Rid coma id
'''
2019-04-04 23:05:36 +00:00
# p[0] will contain an list with all the variable
# names for this production in string format.
if (len(p) == 2):
p[0] = [p[1]]
else:
p[0] = p[1] + [p[3]]
2019-03-21 20:20:55 -06:00
2019-04-22 14:47:49 -05:00
2019-03-21 20:20:55 -06:00
def p_Tipo(p):
'''
Tipo : integer
| real
'''
2019-04-04 23:05:36 +00:00
# p[0] will contain the type in string format
p[0] = p[1]
2019-03-21 20:20:55 -06:00
2019-04-22 14:47:49 -05:00
2019-03-21 20:20:55 -06:00
def p_Dim(p):
'''
Dim : openBra int closedBra
| openBra int closedBra openBra int closedBra
|
'''
2019-04-22 14:47:49 -05:00
2019-03-21 20:20:55 -06:00
def p_F(p):
'''
F : F subroutine id B end subroutine
|
'''
2019-04-22 14:47:49 -05:00
2019-03-21 20:20:55 -06:00
def p_B(p):
'''
B : B S
|
'''
2019-04-22 14:47:49 -05:00
2019-03-21 20:20:55 -06:00
def p_S(p):
'''
S : Dimensional action_7 equals EA action_8
2019-03-21 23:13:56 -06:00
| id parens
2019-03-21 20:20:55 -06:00
| read RDimensional
| print RDimOrString
| if action_16 Relif ElseOrEmpty end if action_20
2019-03-21 23:13:56 -06:00
| do id equals EA coma EA IntOrEmpty then B end do
| do then action_21 B action_22 end do
2019-03-21 20:20:55 -06:00
| swap Dimensional coma Dimensional
| exit action_23
2019-03-21 20:20:55 -06:00
'''
# Adjust the action to support matrices
2019-04-22 14:47:49 -05:00
2019-03-21 20:20:55 -06:00
def p_Dimensional(p):
'''
Dimensional : id DimensionsOrEmpty
'''
p[0] = p[1]
2019-03-21 20:20:55 -06:00
def p_DimensionsOrEmpty(p):
'''
DimensionsOrEmpty : openParen EA ComaEAOrEmpty closedParen
|
'''
2019-04-22 14:47:49 -05:00
2019-03-21 20:20:55 -06:00
def p_ComaEAOrEmpty(p):
'''
ComaEAOrEmpty : coma EA
|
'''
2019-04-22 14:47:49 -05:00
2019-03-21 20:20:55 -06:00
def p_RDimensional(p):
'''
RDimensional : Dimensional
2019-03-21 21:09:36 -06:00
| RDimensional coma Dimensional
2019-03-21 20:20:55 -06:00
'''
2019-04-22 14:47:49 -05:00
2019-03-21 20:20:55 -06:00
def p_RDimOrString(p):
'''
RDimOrString : DimOrString
| RDimOrString coma DimOrString
'''
2019-04-22 14:47:49 -05:00
2019-03-21 20:20:55 -06:00
def p_DimOrString(p):
'''
DimOrString : Dimensional
| string
'''
2019-04-22 14:47:49 -05:00
2019-03-21 20:20:55 -06:00
def p_Relif(p):
'''
Relif : openParen EL closedParen action_17 then B
| Relif elif action_18 openParen EL closedParen action_17 then B
2019-03-21 20:20:55 -06:00
'''
2019-04-22 14:47:49 -05:00
2019-03-21 20:20:55 -06:00
def p_ElseOrEmpty(p):
'''
ElseOrEmpty : else action_19 B
2019-03-21 20:20:55 -06:00
|
'''
2019-04-22 14:47:49 -05:00
2019-03-21 20:20:55 -06:00
def p_IntOrEmpty(p):
'''
IntOrEmpty : coma int
|
'''
2019-04-22 14:47:49 -05:00
2019-03-21 20:20:55 -06:00
def p_EA(p):
'''
EA : MultDiv
| EA SumOrSub action_3 MultDiv action_4
2019-03-21 20:20:55 -06:00
'''
2019-03-21 20:20:55 -06:00
def p_SumOrSub(p):
'''
SumOrSub : plus
| minus
'''
p[0] = p[1]
2019-03-21 21:09:36 -06:00
2019-04-22 14:47:49 -05:00
2019-03-21 21:09:36 -06:00
def p_MultDiv(p):
'''
MultDiv : EAParens
| MultDiv MDSymbols action_5 EAParens action_6
2019-03-21 21:09:36 -06:00
'''
2019-04-22 14:47:49 -05:00
2019-03-21 21:09:36 -06:00
def p_MDSymbols(p):
'''
MDSymbols : mul
| div
'''
p[0] = p[1]
2019-03-21 21:09:36 -06:00
2019-04-22 14:47:49 -05:00
2019-03-21 21:09:36 -06:00
def p_EAParens(p):
'''
EAParens : EItem
| openParen EA closedParen
'''
2019-04-22 14:47:49 -05:00
2019-03-21 21:09:36 -06:00
def p_EL(p):
'''
EL : AND
| EL or action_10 AND action_9
2019-03-21 21:09:36 -06:00
'''
2019-04-22 14:47:49 -05:00
2019-03-21 21:09:36 -06:00
def p_AND(p):
'''
AND : Equality
| AND and action_12 Equality action_11
2019-03-21 21:09:36 -06:00
'''
2019-04-22 14:47:49 -05:00
2019-03-21 21:09:36 -06:00
def p_Equality(p):
'''
Equality : EItem EQSymbols action_13 EItem action_14
2019-03-21 21:09:36 -06:00
| openParen EL closedParen
| not EL action_15
2019-03-21 21:09:36 -06:00
'''
2019-04-22 14:47:49 -05:00
2019-03-21 21:09:36 -06:00
def p_EItem(p):
'''
EItem : Dimensional action_1
| int action_2
| rea action_2_rea
2019-03-21 21:09:36 -06:00
'''
2019-04-22 14:47:49 -05:00
2019-03-21 21:09:36 -06:00
def p_EQSymbols(p):
'''
EQSymbols : less
| more
| doubleEquals
| notEquals
| lessEquals
| moreEquals
'''
p[0] = p[1]
2019-03-21 21:09:36 -06:00
2019-04-22 14:47:49 -05:00
# ----------------------------------------------------------------------------
# -----------------------------PARSER ACTIONS---------------------------------
# ----------------------------------------------------------------------------
def p_action_1(p):
"action_1 :"
if p[-1] not in symbols:
raise Exception(f'The variable {p[-1]} was not declared')
direction = symbols[p[-1]]['direction']
sType = symbols[p[-1]]['type']
operandsStack.append(f'${direction}')
typesStack.append(sType)
def p_action_2(p):
"action_2 :"
operandsStack.append(p[-1])
typesStack.append('integer')
2019-04-22 14:47:49 -05:00
def p_action_2_rea(p):
"action_2_rea :"
operandsStack.append(p[-1])
typesStack.append('real')
2019-04-22 14:47:49 -05:00
def p_action_3(p):
"action_3 :"
operatorsStack.append(p[-1])
2019-04-22 14:47:49 -05:00
def p_action_4(p):
"action_4 :"
if (peek(operatorsStack) == '+' or peek(operatorsStack) == '-'):
global quadrupletIndex
global avail
operator = operatorsStack.pop()
operand2 = operandsStack.pop()
operand1 = operandsStack.pop()
type2 = typesStack.pop()
type1 = typesStack.pop()
resultType = resultingType(operator, type1, type2)
temp = avail.pop(0)
operandsStack.append(temp)
typesStack.append(resultType)
2019-04-22 14:47:49 -05:00
resultQuadruplets.append(str(
operator) + ' ' + str(operand1) + ' ' + str(operand2) + ' ' + str(temp) + '\n')
quadrupletIndex += 1
if (isTemp(operand2)):
avail = [operand2] + avail
if (isTemp(operand1)):
avail = [operand1] + avail
def p_action_5(p):
"action_5 :"
operatorsStack.append(p[-1])
def p_action_6(p):
"action_6 :"
if (peek(operatorsStack) == '*' or peek(operatorsStack) == '/'):
global quadrupletIndex
global avail
operator = operatorsStack.pop()
operand2 = operandsStack.pop()
operand1 = operandsStack.pop()
type2 = typesStack.pop()
type1 = typesStack.pop()
resultType = resultingType(operator, type1, type2)
temp = avail.pop(0)
operandsStack.append(temp)
typesStack.append(resultType)
2019-04-22 14:47:49 -05:00
resultQuadruplets.append(str(
operator) + ' ' + str(operand1) + ' ' + str(operand2) + ' ' + str(temp) + '\n')
quadrupletIndex += 1
if (isTemp(operand2)):
avail = [operand2] + avail
if (isTemp(operand1)):
avail = [operand1] + avail
def p_action_7(p):
"action_7 :"
if p[-1] not in symbols:
raise Exception(f'The variable {p[-1]} was not declared')
direction = symbols[p[-1]]['direction']
sType = symbols[p[-1]]['type']
operandsStack.append(f'${direction}')
typesStack.append(sType)
def p_action_8(p):
"action_8 :"
global quadrupletIndex
global avail
operand2 = operandsStack.pop()
operand1 = operandsStack.pop()
type2 = typesStack.pop()
type1 = typesStack.pop()
# Result type only gets called to make sure the types are compatible.
resultingType('=', type1, type2)
2019-04-22 14:47:49 -05:00
resultQuadruplets.append('= ' + str(operand2) +
' ' + str(operand1) + '\n')
quadrupletIndex += 1
# Return the operand to the availbale if it is a temporal.
if (isTemp(operand2)):
avail = [operand2] + avail
2019-04-22 14:47:49 -05:00
def p_action_9(p):
"action_9 :"
if (peek(operatorsStack) == '.or.'):
global quadrupletIndex
global avail
operator = operatorsStack.pop()
operand2 = operandsStack.pop()
operand1 = operandsStack.pop()
type2 = typesStack.pop()
type1 = typesStack.pop()
resultType = resultingType(operator, type1, type2)
temp = avail.pop(0)
operandsStack.append(temp)
typesStack.append(resultType)
2019-04-22 14:47:49 -05:00
resultQuadruplets.append(str(
operator) + ' ' + str(operand1) + ' ' + str(operand2) + ' ' + str(temp) + '\n')
quadrupletIndex += 1
if (isTemp(operand2)):
avail = [operand2] + avail
if (isTemp(operand1)):
avail = [operand1] + avail
def p_action_10(p):
"action_10 :"
operatorsStack.append(p[-1])
def p_action_11(p):
"action_11 :"
if (peek(operatorsStack) == '.and.'):
global quadrupletIndex
global avail
operator = operatorsStack.pop()
operand2 = operandsStack.pop()
operand1 = operandsStack.pop()
type2 = typesStack.pop()
type1 = typesStack.pop()
resultType = resultingType(operator, type1, type2)
temp = avail.pop(0)
operandsStack.append(temp)
typesStack.append(resultType)
2019-04-22 14:47:49 -05:00
resultQuadruplets.append(str(
operator) + ' ' + str(operand1) + ' ' + str(operand2) + ' ' + str(temp) + '\n')
quadrupletIndex += 1
if (isTemp(operand2)):
avail = [operand2] + avail
if (isTemp(operand1)):
avail = [operand1] + avail
def p_action_12(p):
"action_12 :"
operatorsStack.append(p[-1])
def p_action_13(p):
"action_13 :"
operatorsStack.append(p[-1])
def p_action_14(p):
"action_14 :"
if (peek(operatorsStack) in kEqualityOperators):
global quadrupletIndex
global avail
operator = operatorsStack.pop()
operand2 = operandsStack.pop()
operand1 = operandsStack.pop()
type2 = typesStack.pop()
type1 = typesStack.pop()
resultType = resultingType(operator, type1, type2)
temp = avail.pop(0)
operandsStack.append(temp)
typesStack.append(resultType)
2019-04-22 14:47:49 -05:00
resultQuadruplets.append(str(
operator) + ' ' + str(operand1) + ' ' + str(operand2) + ' ' + str(temp) + '\n')
quadrupletIndex += 1
if (isTemp(operand2)):
avail = [operand2] + avail
if (isTemp(operand1)):
avail = [operand1] + avail
def p_action_15(p):
"action_15 :"
if (peek(typesStack) is not 'bool'):
raise Exception("Cannot use .not. with non boolean")
global quadrupletIndex
operand1 = peek(operandsStack)
2019-04-22 14:47:49 -05:00
resultQuadruplets.append('.not. ' + str(operand1) +
' ' + str(operand1) + '\n')
def p_action_16(p):
"action_16 :"
jumpsStack.append('$')
2019-04-22 14:47:49 -05:00
def p_action_17(p):
"action_17 :"
global quadrupletIndex
global avail
operand1 = operandsStack.pop()
type1 = typesStack.pop()
if (type1 is not 'bool'):
2019-04-22 14:47:49 -05:00
raise Exception(
'Can\'t use non logical expression as conditional for if')
jumpsStack.append(quadrupletIndex)
resultQuadruplets.append('gotoF ' + str(operand1) + ' _\n')
quadrupletIndex += 1
if (isTemp(operand1)):
avail = [operand1] + avail
def p_action_18(p):
"action_18 :"
global quadrupletIndex
resultQuadruplets.append('goto _\n')
quadrupletIndex += 1
Dir = jumpsStack.pop()
fillGoto(Dir, quadrupletIndex)
jumpsStack.append(quadrupletIndex - 1)
def p_action_19(p):
"action_19 :"
global quadrupletIndex
resultQuadruplets.append('goto _\n')
quadrupletIndex += 1
Dir = jumpsStack.pop()
fillGoto(Dir, quadrupletIndex)
jumpsStack.append(quadrupletIndex - 1)
def p_action_20(p):
"action_20 :"
while(peek(jumpsStack) is not '$'):
Dir = jumpsStack.pop()
fillGoto(Dir, quadrupletIndex)
jumpsStack.pop()
def p_action_21(p):
"action_21 :"
jumpsStack.append(quadrupletIndex)
exitsStack.append('$')
def p_action_22(p):
"action_22 :"
global resultQuadruplets
global quadrupletIndex
Dir = jumpsStack.pop()
resultQuadruplets.append(f'goto {Dir}\n')
quadrupletIndex += 1
while(peek(exitsStack) != '$'):
Dir = exitsStack.pop()
fillGoto(Dir, quadrupletIndex)
exitsStack.pop()
def p_action_23(p):
"action_23 :"
global quadrupletIndex
global quadrupletIndex
exitsStack.append(quadrupletIndex)
resultQuadruplets.append('goto _\n')
quadrupletIndex += 1
2019-03-21 21:09:36 -06:00
def p_error(p):
print('XXX Invalid program')
2019-03-21 22:59:22 -06:00
print(p)
2019-03-21 21:09:36 -06:00
2019-04-22 14:47:49 -05:00
2019-03-21 21:09:36 -06:00
parser = yacc.yacc()
2019-04-12 05:55:09 +00:00
2019-04-22 14:47:49 -05:00
# ----------------------------------------------------------------------------
# --------------------INTERMEDIATE CODE FILE GENERATION-----------------------
# ----------------------------------------------------------------------------
2019-04-12 05:55:09 +00:00
if (len(sys.argv) > 1):
programName = sys.argv[1]
programFile = open(programName, "r")
resultFile = open(programName + '.out', "w+")
# This is neccessary because the read method parses literal ends
2019-04-04 23:05:36 +00:00
# of lines as \\n instead of \n.
program = programFile.read().replace('\\n', '\n')
parser.parse(program)
resultFile.writelines(resultQuadruplets)
# Close the files.
programFile.close()
resultFile.close()
else:
raise Exception('''
No file name was provided.
Please add the file name as a command line argument
Example: fort.py test.fort
''')