Skip to content

Commit

Permalink
feat(klvm): add KoiLang runner
Browse files Browse the repository at this point in the history
Fix bugs in setup.py.
Add main runner.
  • Loading branch information
Ovizro committed Aug 25, 2022
1 parent 0773b09 commit efa8d5b
Show file tree
Hide file tree
Showing 9 changed files with 115 additions and 13 deletions.
1 change: 1 addition & 0 deletions .github/workflows/python-publish.yml
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ jobs:
run: |
python -m pip install --upgrade pip
pip install setuptools --upgrade
pip install wheel
- name: Build package
run: |
python setup.py build_ext --inplace
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ All the arguments can be put together
Kola module provides a fast way to convert KoiLang command
to a python function call.

Above command `#draw` will convert to calling below:
Above command `#draw` will convert to function calling below:

```py
draw(
Expand Down
2 changes: 2 additions & 0 deletions kola/__init__.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
from .lexer import BaseLexer, FileLexer, StringLexer
from .parser import Parser
from .klvm import KoiLang, kola_command, kola_text, kola_number
from .version import __version__, version_info
from .exception import *

__all__ = [
"KoiLang",
"BaseLexer",
"FileLexer",
"StringLexer",
Expand Down
31 changes: 30 additions & 1 deletion kola/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
from argparse import ArgumentParser
from typing import Any, Callable, Dict, Tuple

from kola.klvm import KoiLang, KoiLangMeta, kola_command, kola_text

from . import BaseLexer, FileLexer, StringLexer, Parser, __version__


Expand All @@ -12,6 +14,16 @@ def wrapper(*args, **kwds) -> None:
return wrapper


class KoiLangMain(KoiLang):
@kola_command
def version(self):
print(__version__)

@kola_text
def text(self, text: str):
print(text)


parser = ArgumentParser("kola")
parser.add_argument("file", default=None, nargs="?")
parser.add_argument("-i", "--inline", help="parse inline string")
Expand All @@ -20,6 +32,7 @@ def wrapper(*args, **kwds) -> None:

namespace = parser.parse_args()


if namespace.file:
lexer = FileLexer(namespace.file)
elif namespace.inline:
Expand All @@ -33,4 +46,20 @@ def wrapper(*args, **kwds) -> None:
print(i)
elif namespace.debug == "grammar":
print(f"KoiLang Grammar Debugger {__version__} in file \"{lexer.filename}\" on {sys.platform}")
Parser(lexer, CommandDebugger).exec_() # type: ignore
Parser(lexer, CommandDebugger).exec_()
else:
print(f"KoiLang Runner in file \"{lexer.filename}\" on {sys.platform}")
if namespace.parser:
vdict = {}
with open(namespace.parser) as f:
exec(f.read(), {}, vdict)
for i in vdict.values():
if isinstance(i, KoiLangMeta):
command_cls = i
break
else:
raise TypeError("no KoiLang command set found")
else:
command_cls = KoiLangMain

Parser(lexer, command_cls().command_set).exec_()
2 changes: 1 addition & 1 deletion kola/_helper.h
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ static const char* get_format(int code) {
case 201:
case 202:
ERR_MSG(keyword must be a literal);
case 203:
case 210:
ERR_MSG(bad argument count);
}

Expand Down
69 changes: 69 additions & 0 deletions kola/klvm.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
from argparse import ArgumentParser
import sys
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
from types import MethodType
from .lexer import BaseLexer, StringLexer, FileLexer
from .parser import Parser


class KoiLangCommand(object):
__slots__ = ["__name__", "__func__"]

def __init__(self, name: str, func: Callable) -> None:
self.__name__ = name
self.__func__ = func

def __get__(self, instance: Any, owner: type) -> Callable:
return self.__func__.__get__(instance, owner)

def __call__(self, *args: Any, **kwds: Any) -> Any:
return self.__func__(*args, **kwds)


class KoiLangMeta(type):
"""
Metaclass for KoiLang class
"""
__command_field__: List[KoiLangCommand]

def __new__(cls, name: str, base: Tuple[type, ...], attr: Dict[str, Any]):
__command_field__ = [i for i in attr.values() if isinstance(i, KoiLangCommand)]
attr["__command_field__"] = __command_field__

return super().__new__(cls, name, base, attr)

def get_command_set(self, instance: Any) -> Dict[str, MethodType]:
return {i.__name__: MethodType(i.__func__, instance) for i in self.__command_field__}


class KoiLang(metaclass=KoiLangMeta):
"""
Main class for KoiLang parsing.
"""
__slots__ = ["command_set"]

def __init__(self) -> None:
self.command_set = self.__class__.get_command_set(self)

def __getitem__(self, key: str) -> Callable:
return self.command_set[key]

def parse(self, text: Optional[str] = None) -> None:
if text is None:
lexer = BaseLexer()
else:
lexer = StringLexer(text)
Parser(lexer, self.command_set).exec_()

def parse_file(self, path: str) -> None:
Parser(FileLexer(path), self.command_set).exec_()


def kola_command(func: Callable) -> KoiLangCommand:
return KoiLangCommand(func.__name__, func)

def kola_text(func: Callable) -> KoiLangCommand:
return KoiLangCommand("@text", func)

def kola_number(func: Callable) -> KoiLangCommand:
return KoiLangCommand("@number", func)
14 changes: 7 additions & 7 deletions kola/parser.c

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions kola/version.py
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
__version__ = "0.1.0a2"
version_info = (0, 1, 0, "alpha", 2)
__version__ = "0.1.0b0"
version_info = (0, 1, 0, "beta", 0)
3 changes: 2 additions & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@
_home = os.path.dirname(__file__)

extensions = [
Extension("kola.lexer", ["kola/lexer" + FILE_SUFFIX]),
Extension("kola.lexer", ["kola/lexer" + FILE_SUFFIX, "kola/lex.yy.c"]),
Extension("kola.parser", ["kola/parser" + FILE_SUFFIX])
]
if USE_CYTHON:
Expand All @@ -59,6 +59,7 @@
maintainer_email="[email protected]",
license="Apache 2.0",

url="https://github.com/Ovizro/Kola",
packages=["kola"],
python_requires=">=3.6",
package_data={'':["*.pyi", "*.pxd", "*.h"]},
Expand Down

0 comments on commit efa8d5b

Please sign in to comment.