代码拉取完成,页面将自动刷新
# Todo:
# Logic - finished
import tobylanginfo
import os
import yaml
from builtins_regexs import *
from lang_builtins import *
curdir = os.path.dirname(os.path.abspath(__file__))
def isp(line):
space = 0
for i in range(len(line)):
if line[i] == " ":
space += 1
else:
break
return space
CPP_EXTS = {
"namespace-std": "using namespace std;",
"stringinput": "string stringinput(string prompt=\"\"){string a;cout<<prompt;cin>>a;return a;};"
}
CPP_INCLUDES = ["iostream", "cstring"]
def parsecon(regex:str):
return PARSE_CON+regex+PARSE_CON
def cpp(code):
code="import __builtin__vector_utils__\n"+code
def error_wrap(msg):
error(msg, True)
res_code = "%includes%%exts% \nint main(){%entry_code%return 0;}"
exts = ""
for i in CPP_EXTS:
exts += f"/*ext:{i}*/"+CPP_EXTS[i]+"\n"
includes = ""
for i in CPP_INCLUDES:
includes += f"#include<{i}>\n"
res = ""
lineno = 1
codelines=code.splitlines()
for i in range(len(codelines)):
if re.match(rf"{END_RE}(.*?)",nisp(codelines[i])):
bracket,line=END_RE,nisp(codelines[i])[1:].strip()
a=isp(codelines[i])*" "+bracket+"\n"+isp(codelines[i])*" "+line+"\n"
codelines[i]=a
code="\n".join(codelines)
#print(code)
codelines=code.splitlines()
for line in codelines:
# For
if re.match(parsecon(FOR_START_RE), nisp(line)):
var, start, end, step = re.match(
FOR_START_RE, nisp(line)).group(1, 2, 3, 4)
res += isp(line) * " " + FOR_START_CPP \
.replace("%var%", var) \
.replace("%start%", start) \
.replace("%end%", end) \
.replace("%step%", step) + "\n"
# import lib
elif re.match(parsecon(IMPORT_RE), nisp(line)):
# error_wrap(f"ImportError: no lib called {importlib} [line {lineno}]")
importlib = re.match(IMPORT_RE, nisp(line)).group(1)
sitelib = os.path.join(curdir, "lib", importlib, "config.yml")
stdlib = os.path.join(curdir, "stdlib", importlib, "config.yml")
filepath = os.path.join(importlib, "config.yml")
libpath = ""
if(os.path.exists(stdlib)):
libpath = stdlib
elif(os.path.exists(filepath)):
libpath = filepath
elif(os.path.exists(sitelib)):
libpath = sitelib
else:
error_wrap(
f"ImportError: no lib called {importlib} [line {lineno}]")
if(libpath):
with open(libpath, "r", encoding="utf-8")as fp:
data = yaml.load(fp, yaml.FullLoader)
new_exts = data["cpp_exts"]
new_includes = data["cpp_includes"]
new_funcs = data["functions"]
# print(new_funcs)
for i in new_includes:
includes += f"#include<{i}>\n"
for i in new_exts:
exts += f"/*ext:{i}*/"+new_exts[i]+"\n"
for i in new_funcs:
argdata = new_funcs[i]["args"]
py_code = new_funcs[i]["python"]
argIndex = 0
argToIndex = {}
for arg in argdata:
argToIndex[arg] = argIndex
argIndex += 1
class newFunc(BaseFunction):
cppcode = new_funcs[i]["cpp"]
argIndex=argToIndex.copy()
argdat=argdata[:]
def __init__(self) -> None:
super().__init__()
def to_cpp(self, cppargs):
cppcode=self.cppcode
for a in self.argdat:
cppcode = cppcode.replace(
f"${a}", cppargs[self.argIndex[a]].to_cpp(cppargs[self.argIndex[a]].value))
return cppcode
exec(f'class {i}_func(newFunc):pass')
exec(f'BUILTIN_FUNCS[i] = {i}_func')
del newFunc
elif re.match(parsecon(IF_START_RE), nisp(line)):
elif_if, logic = re.match(IF_START_RE, nisp(line)).group(1, 2)
if elif_if == "elif":
elif_if = "else if"
logic = logic.replace("true", "True").replace("false", "False")
res += isp(line) * " " + IF_START_CPP.replace("%if%",
elif_if).replace("%logic%", logic) + "\n"
elif END_RE == nisp(line).strip():
res += isp(line) * " " + "}\n"
elif ELSE_RE == nisp(line):
res += isp(line) * " " + ELSE_CPP + "\n"
# Function calling
elif re.match(parsecon(FUNC_CALL_RE), nisp(line)):
funcname, args = get_func_call(nisp(line))
if BUILTIN_FUNCS.get(funcname.strip()):
FuncObj = BUILTIN_FUNCS.get(funcname.strip())()
funcCode = FuncObj.to_cpp(args)
res += isp(line) * " " + funcCode + ";\n"
else:
error_wrap(
f"NameError: no func called {funcname} [line {lineno}]")
elif re.match(parsecon(VARIBLE_CREATE_RE), nisp(line)):
# print(line)
typevar, var = re.match(VARIBLE_CREATE_RE, nisp(line)).groups()
if(re.match("(.*)<(.*)>",typevar)):
name=re.match("(.*)<.*>",typevar).group(1)
if not BUILTIN_DTYPES.get(name):
error(
f"TypeError: Unknown Varible Type when creating var {var} [line {lineno}]")
matchtype=BUILTIN_DTYPES.get(name)
typelist=[]
for i in re.match(".*<(.*)>",typevar).group(1).split(","):
x=i.strip()
if not BUILTIN_TYPES.get(x):
error(
f"TypeError: Unknown Varible Type when creating var {var} [line {lineno}]")
typelist.append(BUILTIN_TYPES_TO_CPP[x])
temp_typelist_str=",".join(typelist)
to_cpp_=BUILTIN_TYPES_TO_CPP[matchtype].replace("%type%",temp_typelist_str)
res += isp(line) * " " + \
f"{to_cpp_} {var};\n"
else:
res += isp(line) * " " + \
f"{BUILTIN_TYPES_TO_CPP[typevar]} {var};\n"
elif re.match(parsecon(VARIBLE_SET_RE), nisp(line)):
var, value = re.match(VARIBLE_SET_RE, nisp(line)).groups()
# print(line,value,re.match(FUNC_CALL_RE, value))
if re.match(FUNC_CALL_RE, value):
funcname, args = get_func_call(value)
# print(args)
if BUILTIN_FUNCS.get(funcname):
FuncObj = BUILTIN_FUNCS.get(funcname)()
funcCode = FuncObj.to_cpp(args)
res += isp(line) * " " + f"{var}={funcCode};\n"
else:
error(
f"NameError: no func called {funcname} [line {lineno}]")
else:
if not match_type(value):
error(
f"TypeError: Unknown Type when changing var {var} [line {lineno}]")
t = value
if(match_type(value) != "var"):
t = BUILTIN_TYPES[match_type(value)]().to_cpp(value)
# print("a", t, match_type(value))
res += isp(line) * " " + f"{var}={t};\n"
elif not line:
res += "\n"
elif match_type(nisp(line)):
# print(line,match_type(nisp(line)))
if match_type(nisp(line)) == "var":
res += line + "\n"
continue
t = BUILTIN_TYPES[match_type(nisp(line))]()
res += isp(line) * " " + t.to_cpp(nisp(line)) + "\n"
else:
error_wrap(f"Error: Unknown Syntax [line {lineno}]\n\t> {line}")
# in cpp we should replace the logic operators.
if re.match(LOGICS_RE, nisp(line)):
for i, j in enumerate(LOGICS):
res += nisp(line).replace(j, LOGICS_CPP[i])
lineno += 1
return res_code.replace("%entry_code%", res)\
.replace("%exts%", exts)\
.replace("%includes%", includes)
def nisp(line):
return line.replace(isp(line) * " ", "")
PYTHON_EXTS = {
# "tobylang-version": f"def tobylang_ver():return \"{tobylanginfo.VERSION}\""
}
# PYTHON_INCLUDES = ["random"]
PYTHON_INCLUDES = []
def py3_core(code, linenum=1, linenum_format="%num%", exit_1=True,return_exts_includes=False):
def error_wrap(msg):
error(msg, exit_1)
if(return_exts_includes):
code="import __builtin__vector_utils__\n"+code
exts=""
res = ""
includes=""
real_lineno = linenum
linenum_format.replace("%num%", str(real_lineno))
codelines=code.splitlines()
for i in range(len(codelines)):
if re.match(rf"{END_RE}(.*?)",nisp(codelines[i])):
bracket,line=END_RE,nisp(codelines[i])[1:].strip()
a=isp(codelines[i])*" "+bracket+"\n"+isp(codelines[i])*" "+line+"\n"
codelines[i]=a
code="\n".join(codelines)
#print(code)
codelines=code.splitlines()
for line in codelines:
# real_lineno=linenum
lineno = linenum_format.replace("%num%", str(real_lineno))
# print(real_lineno,nisp(line),isp(line))
# For
if re.match(parsecon(FOR_START_RE), nisp(line)):
var, start, end, step = re.match(
FOR_START_RE, nisp(line)).group(1, 2, 3, 4)
res += isp(line) * " " + FOR_START_PYTHON \
.replace("%var%", var) \
.replace("%start%", start) \
.replace("%end%", end) \
.replace("%step%", step) + "\n"
elif re.match(parsecon(IMPORT_RE), nisp(line)):
# error_wrap(f"ImportError: no lib called {importlib} [line {lineno}]")
importlib = re.match(IMPORT_RE, nisp(line)).group(1)
# print(importlib,nisp(line))
sitelib = os.path.join(curdir, "lib", importlib, "config.yml")
stdlib = os.path.join(curdir, "stdlib", importlib, "config.yml")
filepath = os.path.join(importlib, "config.yml")
libpath = ""
if(os.path.exists(filepath)):
libpath = filepath
elif(os.path.exists(stdlib)):
libpath = stdlib
elif(os.path.exists(sitelib)):
libpath = sitelib
else:
error_wrap(
f"ImportError: no lib called {importlib} [line {lineno}]")
if(libpath):
with open(libpath, "r", encoding="utf-8")as fp:
data = yaml.load(fp, yaml.FullLoader)
# new_cppexts=data["cpp_exts"]
# new_cppincludes=data["cpp_includes"]
new_exts = data["python_exts"]
new_includes = data["python_includes"]
new_funcs = data["functions"]
for i in new_includes:
if(not return_exts_includes):
res += f"import {i}\n"
else:
includes += f"import {i}\n"
for i in new_exts:
if(not return_exts_includes):
res += f"# exts:{i}\n"+new_exts[i]+"\n"
else:
exts += f"# exts:{i}\n"+new_exts[i]+"\n"
for i in new_funcs:
argdata = new_funcs[i]["args"]
py_code = new_funcs[i]["python"]
argIndex = 0
argToIndex = {}
for arg in argdata:
argToIndex[arg] = argIndex
argIndex += 1
class newFunc(BaseFunction):
pycode = new_funcs[i]["python"]
argIndex=argToIndex.copy()
argdat=argdata[:]
def __init__(self) -> None:
super().__init__()
def to_python3(self, pyargs):
pycode=self.pycode
for a in self.argdat:
pycode = pycode.replace(
f"${a}", pyargs[self.argIndex[a]].to_python3(pyargs[self.argIndex[a]].value))
return pycode
exec(f'class {i}_func(newFunc):pass')
exec(f'BUILTIN_FUNCS[i] = {i}_func')
del newFunc
# If Logic
elif re.match(parsecon(IF_START_RE), nisp(line)):
elif_if, logic = re.match(IF_START_RE, nisp(line)).group(1, 2)
logic = logic.replace("true", "True").replace("false", "False")
res += isp(line) * " " + IF_START_PYTHON.replace("%if%",
elif_if).replace("%logic%", logic) + "\n"
elif END_RE == nisp(line):
res += isp(line) * " " + "\n"
elif ELSE_RE == nisp(line):
res += isp(line) * " " + ELSE_PYTHON + "\n"
# Function calling
elif re.match(parsecon(FUNC_CALL_RE), nisp(line)):
funcname, args = get_func_call(nisp(line))
if BUILTIN_FUNCS.get(funcname.strip()):
FuncObj = BUILTIN_FUNCS.get(funcname.strip())()
funcCode = FuncObj.to_python3(args)
res += isp(line) * " " + funcCode + "\n"
else:
error_wrap(
f"NameError: no func called {funcname} [line {lineno}]")
# Varible Creating
elif re.match(VARIBLE_CREATE_RE, nisp(line)):
typevar, var = re.match(VARIBLE_CREATE_RE, nisp(line)).groups()
if(re.match("(.*)<(.*)>",typevar)):
name=re.match("(.*)<.*>",typevar).group(1)
if not BUILTIN_DTYPES.get(name):
error(
f"TypeError: Unknown Varible Type when creating var {var} [line {lineno}]")
matchtype=name
for i in re.match(".*<(.*)>",typevar).group(1).split(","):
x=i.strip()
if not BUILTIN_TYPES.get(x):
error(
f"TypeError: Unknown Varible Type when creating var {var} [line {lineno}]")
to_py_=BUILTIN_DTYPES_TO_PY[name]
res += isp(line) * " " + \
f"{var}={to_py_}\n"
else:
vartype=BUILTIN_DTYPES_TO_PY[typevar]
if(not vartype):
vartype="None"
res += isp(line) * " " + \
f"{var}={vartype}\n"
# Varible Value Changing
elif re.match(parsecon(VARIBLE_SET_RE), nisp(line)):
var, value = re.match(VARIBLE_SET_RE, nisp(line)).groups()
# print(line,value,re.match(FUNC_CALL_RE, value))
if re.match(FUNC_CALL_RE, value):
funcname, args = get_func_call(value)
# print(args)
if BUILTIN_FUNCS.get(funcname):
FuncObj = BUILTIN_FUNCS.get(funcname)()
funcCode = FuncObj.to_python3(args)
res += isp(line) * " " + f"{var}={funcCode}\n"
else:
error(
f"NameError: no func called {funcname} [line {lineno}]")
else:
if not match_type(value):
error(
f"TypeError: Unknown Type when changing var {var} [line {lineno}]")
t = value
if(match_type(value) != "var"):
t = BUILTIN_TYPES[match_type(value)]().to_python3(value)
# print("a", t, match_type(value))
res += isp(line) * " " + f"{var}={t}\n"
# Type on line!?
elif match_type(nisp(line)):
if match_type(nisp(line)) == "var":
res += isp(line) * " " + nisp(line) + "\n"
continue
t = BUILTIN_TYPES[match_type(nisp(line))]()
res += isp(line) * " " + t.to_python3(nisp(line)) + "\n"
elif not line:
res += "\n"
else:
error_wrap(f"Error: Unknown Syntax [line {lineno}]\n\t> {line}")
real_lineno += 1
if(return_exts_includes):
return res,exts,includes
return res
def python3(code):
exts = ""
for i in PYTHON_EXTS:
exts += f"# ext:{i}\n"+PYTHON_EXTS[i]+"\n"
includes = ""
for i in PYTHON_INCLUDES:
includes += f"import {i}\n"
res_code = "%includes%%exts% \n%entry_code%"
res,exts2,includes2 = py3_core(code,return_exts_includes=True)
exts+=exts2
includes+=includes2
return res_code.replace("%entry_code%", res)\
.replace("%exts%", exts)\
.replace("%includes%", includes)
def python3_interactive(code):
res_code = "%entry_code%"
# BUILTIN_FUNCS["intersave"]=InteractiveSave
res = py3_core(code, linenum_format="<interactive>", exit_1=False)
return res_code.replace("%entry_code%", res)
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。