Skip to content

Commit

Permalink
Add "import" syntax
Browse files Browse the repository at this point in the history
  • Loading branch information
0x24a committed Aug 20, 2023
1 parent ff832da commit df136e6
Show file tree
Hide file tree
Showing 7 changed files with 72 additions and 10 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,6 @@ Examples:
- FUNCTIONS 用户预定义的函数,动态生成/分析.
- MAIN 主程序,也就是int main.
## 五、目前进度
函数,变量,循环,条件判断
函数,变量,循环,条件判断,导入
## 六、待办事项
去除let语句,自动检测目标值类型
4 changes: 4 additions & 0 deletions configure-sblang2c-alias
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
#!/usr/bin/bash
echo "Add this to your ~/.bashrc or ~/.zshrc or another shell's 'read command' file."
WORKDIR=$(pwd)
echo "alias sblang2c=\"python3 $WORKDIR/sblang2c.py\""
15 changes: 12 additions & 3 deletions converter.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from uuid import uuid4
from logging import debug
from os import path

class Function:
def __init__(self):
Expand Down Expand Up @@ -94,6 +95,11 @@ def let(runtime,line):
return f"{typeof} {name};"
content=line[1].split(" ",2)[2]
return f"{typeof} {name}={content};"
def fromimport(runtime,line):
runtime.externs.add(line[1])
def export(runtime,line):
line=line[1].split(" ")
return "extern \"C\" {"+f"{line[0]} {line[1]}"+";}"
bulitins=(
{
"end":"}",
Expand All @@ -109,7 +115,9 @@ def let(runtime,line):
"var":var,
"let":let,
"define":define,
"return":returns
"return":returns,
"import":fromimport,
"export":export
}
)
COMMENT="""
Expand Down Expand Up @@ -156,7 +164,7 @@ def translate(self,runtime,line):
)
class Runtime:
def __init__(self):
self.heads,self.head,self.externs,self.functions,self.main,self.global_checker,self.cache=set(),[],[],[],[],[],{}
self.heads,self.head,self.externs,self.functions,self.main,self.global_checker,self.cache=set(),[],set(),[],[],[],{}
self.type_detector={}
self.loops={}
def translate(self,line,run_checkers=True,return_code=False):
Expand Down Expand Up @@ -186,7 +194,8 @@ def export_final(self):
debug(f"Headers: {self.heads}")
for i in self.heads:
final+=f"#include <{i}>\n"
final+="\n\n".join(self.head+self.externs+self.functions+self.main)
final+="\n\n".join(self.head+self.functions+self.main)
self.externs=list(self.externs)
return final


50 changes: 47 additions & 3 deletions sblang2c.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import converter,sys,os,time,logging
import converter,sys,os,time,logging,secrets
class Timer:
def __init__(self) -> None:
self.stt=0
Expand All @@ -15,6 +15,7 @@ def end(self):
debug="--debug" in argss
gcc_executable="g++"
gcc_extra_args=[]
temps=[]
name_executeable=".".join(filename.split(".")[:-1])
for arg in argss:
arg=arg.split("=",1)
Expand Down Expand Up @@ -59,20 +60,62 @@ def end(self):
if debug:
print()
print(f" {timer.end()} ms")

print('-| Resolving externs')
links=[]
mapping={}
if len(runtime.externs) == 0:
print("-| No externs")
else:
runtime.externs=list(runtime.externs)
print(f"-| Compiling {len(runtime.externs)} head(s)")
for count in range(1,len(runtime.externs)+1):
print(f"- -|{count}/{len(runtime.externs)}: {runtime.externs[count-1]}")
filename=f"_sblang_header_{secrets.token_hex(16)}.h"
temps.append(filename)
with open(runtime.externs[count-1],"r",encoding="utf-8") as f:
modcode=f.read()
with open(filename,"w+") as f:
rt=converter.Runtime()
try:
for i in modcode.splitlines():
rt.translate(i)
except BaseException as e:
print(f"\n! Error when converting: {e}")
from traceback import print_exc
print_exc()
exit(1)
rt.heads=[]
f.write(rt.export_final())
if rt.externs != []:
print("WARN: Multi-layer extern is not supported yet")
mapping.update({runtime.externs[count-1]:filename})
print(f"- -|{count}/{len(runtime.externs)}: {runtime.externs[count-1]}: Success")
new=[]
for i in runtime.externs:
data=mapping.get(i,i)
if data != i:
data=os.getcwd()+"/"+data
runtime.heads.add(data)
print("- -| Writing to temp file",end="",flush=True)
timer.start()
if debug:
print()
with open("_sblang_temp.cpp","w+",encoding="utf-8") as f:
f.write(runtime.export_final())
temps.append("_sblang_temp.cpp")
if debug:
print()
print(f" {timer.end()} ms")
if nocomp:
print("-| Exiting.")
exit(0)
time.sleep(1)
print("-| Compiling with g++")
command=f"{gcc_executable} _sblang_temp.cpp -finput-charset=UTF-8 -std=c++20 -o {name_executeable}"
command=f"{gcc_executable} _sblang_temp.cpp "
for i in links:
command+=f"{i} "
command+=f"-finput-charset=UTF-8 -std=c++20 -o {name_executeable}"
if gcc_extra_args != []:
for i in gcc_extra_args:
command+=" "+i
Expand All @@ -87,5 +130,6 @@ def end(self):
gcc.read()
print(f" {timer.end()} ms")
print("-| Removeing Tempfile")
os.remove("_sblang_temp.cpp")
for temp in temps:
os.remove(temp)
print("-| Exiting Compile.")
3 changes: 0 additions & 3 deletions sblang2c.sh

This file was deleted.

5 changes: 5 additions & 0 deletions test_import.sbl
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
main
import test_import_head.sbl
output "1+1="
output plusOne(1)
end
3 changes: 3 additions & 0 deletions test_import_head.sbl
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
define plusOne num
return (1+num)
define end

0 comments on commit df136e6

Please sign in to comment.