Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/linux/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
简单语言的Python解析器_Python_Linux_Parsing_Recursion_Ebnf - Fatal编程技术网

简单语言的Python解析器

简单语言的Python解析器,python,linux,parsing,recursion,ebnf,Python,Linux,Parsing,Recursion,Ebnf,我被这个计划困住了。由于某种原因,程序不会给我输入的信息。 因此,我试图实现的是一种书面形式,它由我们的p-d和v-lu-tаrаrаrаrаrаrаrаrаrаrаrаrаrаrаrаrаrаrаrаrаrаrаrаrаrаrаrаrаr1072。这是一个非常小的结构,典型的lаnguаgаgаgаmаr。 代码如下: def lexan(): global mitr try: return(next(mitr)) except StopIterati

我被这个计划困住了。由于某种原因,程序不会给我输入的信息。 因此,我试图实现的是一种书面形式,它由我们的p-d和v-lu-tаrаrаrаrаrаrаrаrаrаrаrаrаrаrаrаrаrаrаrаrаrаrаrаrаrаrаrаrаr1072。这是一个非常小的结构,典型的lаnguаgаgаgаmаr。

代码如下:

def lexan():
    global mitr
    try:
        return(next(mitr))
    except StopIteration:
        return('')

def match(lexem):
    global lookahead
    if lexem == lookahead:
        lookahead = lexan()
    else: 
        print('Match Syntax Error  ')
        print('Required  - ' + lexem + 'Received  - ' + lookahead)
        SystemExit()

def prog():
    global lookahead
    let_in_end()
    while lookahead == 'let':
        typeDict.clear()
        valueDict.clear()
        let_in_end()

def decl_list(id):
    global lookahead
    decl(id)
    while lookahead != 'in':
        id = lookahead
        decl(id)


def let_in_end():
    global lookahead
    match('let')
    decl_list(lookahead)
    match('in')  
    expectedType = typeOf(lookahead)
    match('(')
    num = expr(expectedType)
    match(')')
    match('end')
    match(';')
    print(num)

def decl(id):
    global lookahead
    if id in invalidIDs:
        print('System Error. Invalid ID')
        SystemExit()
    valueDict[id] = None
    typeDict[id] = None
    lookahead = lexan()
    match(':')
    typeDict[id] = typeOf(lookahead)
    match('=')
    valueDict[id] = expr(typeDict[id])
    if type(valueDict[id]) != typeDict[id]:
        print('Expression and type Mismatch Declaration')
        SystemExit()
    match(';')

def id_list():
    global lookahead
    # ***check that id hasn't been declared yet in dictionary (type and id_list as key and value?)***
    # ***if not add to dictionary else Syntax error exit********
    # print(lookahead)
    if id():
        # worked
        lookahead = lexan()
    else:
        print("Syntax Errors 1")
        exit(1)
    if match(","):
        # print("FOUND ,")
        id_list()

def expr():  # using variable v, from example in notes
    global lookahead
    v = term()
    tempList = ["+", "-"]
    while (lookahead in tempList):
        if match("+"):
            # print("FOUND +")
            v += term()
        elif match("-"):
            # print("FOUND -")
            v -= term()
        else:
            print("Syntax Errors 3")
            exit(1)
    return v

def typeOf(type):
    global lookahead
    if type == 'int':
        lookahead = lexan()
        return int
    elif type == 'real':
        lookahead = lexan()
        return float
    else:
        print('Must define type as real or int')
        SystemExit()

def expr(exp_type):
    global lookahead
    if lookahead == 'if':
        match('if')
        boolResult = cond()
        lookahead = lexan()
        match('then')
        thenExp = expr(exp_type)
        match('else')
        elseExp = expr(exp_type)
        if boolResult:
            return thenExp
        else: 
            return elseExp
    else:
        termValue = term(exp_type)
        while lookahead == '+' or lookahead == '-':
            if lookahead == '+':
                match('+')
                termValue = termValue + term(exp_type)
            else:
                match('-')
                termValue = termValue - term(exp_type)
        return termValue
    
def term(exp_type):
    global lookahead
    tempVal = factor(exp_type)
    while lookahead == '*' or lookahead == '/':
        if lookahead == '*':
            match('*')
            tempVal = tempVal * (factor(exp_type))
        else:
            match('/')
            tempVal = tempVal / factor(exp_type)
    return tempVal

def factor(exp_type):
    global lookahead
    if lookahead == '(':
        match('(')
        tempValue = expr(exp_type)
        match(')')
        return tempValue
    elif lookahead in valueDict.keys():
        id = lookahead
        lookahead = lexan()
        if typeDict[id] == exp_type:
            return valueDict[id]
        else:
            print('Expected Value Mismatch in Factor')
            SystemExit()
    elif lookahead.find('.') != -1:
        tempValue = float(lookahead)
        lookahead = lexan()
        return tempValue
    elif lookahead.isdigit():
        tempValue = int(lookahead)
        lookahead = lexan()
        return tempValue
    elif lookahead == 'int' or lookahead == 'real':
        typeConvert = typeOf(lookahead)
        lookahead = lexan()
        if lookahead in valueDict.keys():
            if  typeConvert == int:
                match('(')
                tempVar = int(valueDict[lookahead])
                lookahead = lexan()
                match(')')
                return tempVar
            elif typeConvert == float:
                match('(')
                tempVar = float(valueDict[lookahead])
                lookahead = lexan()
                match(')')
                return tempVar
            else:
                print('Type conversion error')
                SystemExit()
        else:
            print('Error. Couldnt find ID')
            SystemExit()
    else:
        print('Factoring Error')
        SystemExit()

import sys

file = open('data.tiny', 'r')
wlist = file.read().split()
mitr = iter(wlist)
lookahead = lexan()
invalidIDs = ["let", "in", "end", "if", "then", "else", "real", "int"]
operators  = ['+', '-', '*', '/']
typeDict = {}
valueDict = {}
prog()
主要问题是,每当我们传递参数时,我都会遇到多个错误,例如expect-;但是得到了-x。我想使用文件名“data.tiny”并包含以下信息:

cat测试。微小:

real m , n = 4.0 , 3.0 ;

let

int x = 5 ;

in

int ( x + x * x )

end ;


let



real m , pi = 10.0 , 3.1416 ;

in

real ( pi * m * m )

end ;  




let  

real x , y = m + n , m - n ;

in

real ( x * y )

end
real y = 3.0 ;

let

int x = 7 ;

in

real ( ( real ( x ) + y ) / ( real ( x ) - y ) )

end;





let 

x = 8 ;

in ( x + y )

end ;
预期产出

三十

314.6

7.0

另一个例子:

real m , n = 4.0 , 3.0 ;

let

int x = 5 ;

in

int ( x + x * x )

end ;


let



real m , pi = 10.0 , 3.1416 ;

in

real ( pi * m * m )

end ;  




let  

real x , y = m + n , m - n ;

in

real ( x * y )

end
real y = 3.0 ;

let

int x = 7 ;

in

real ( ( real ( x ) + y ) / ( real ( x ) - y ) )

end;





let 

x = 8 ;

in ( x + y )

end ;
预期产出

2.5

错误

但我犯了一个错误,似乎我把逻辑搞砸了。每当我设置test.tiny时,以下方法都可以正常工作:

输入

let x : int = 5 ;

in

 int ( x + x * x )

end ;



let r : real = 10.0 ;

pi : real = 3.14156 ;

in

real ( pi * r * r )

end ; 



let a : int = 3 ;

b : real = 0.5 ; 

c : real = b * b ;

in

real ( if a > 5 then b + 1.1 else c )

end ;
输出

let x : int = 5 ;

in

 int ( x + x * x )

end ;



let r : real = 10.0 ;

pi : real = 3.14156 ;

in

real ( pi * r * r )

end ; 



let a : int = 3 ;

b : real = 0.5 ; 

c : real = b * b ;

in

real ( if a > 5 then b + 1.1 else c )

end ;
三十

314.156

0.25

我不确定如果有人能透露一些有用的信息,会有什么潜在的问题