Skip to content
This repository has been archived by the owner on Sep 12, 2024. It is now read-only.

Commit

Permalink
[UPDATE]: Address PR comments
Browse files Browse the repository at this point in the history
  • Loading branch information
amadolid committed Aug 20, 2024
1 parent b3f5a1b commit 861512f
Show file tree
Hide file tree
Showing 12 changed files with 212 additions and 108 deletions.
46 changes: 32 additions & 14 deletions jaclang/cli/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
from jaclang.plugin.builtin import dotgen
from jaclang.plugin.feature import JacCmd as Cmd
from jaclang.plugin.feature import JacFeature as Jac
from jaclang.runtimelib.constructs import Architype
from jaclang.runtimelib.constructs import Architype, WalkerArchitype
from jaclang.runtimelib.machine import JacProgram
from jaclang.utils.helpers import debugger as db
from jaclang.utils.lang_tools import AstTool
Expand Down Expand Up @@ -91,7 +91,7 @@ def run(
base = base if base else "./"
mod = mod[:-4]

jctx = Jac.new_context(base_path=base, session=session)
jctx = Jac.create_context(base_path=base, session=session)

if filename.endswith(".jac"):
ret_module = jac_import(
Expand Down Expand Up @@ -129,6 +129,7 @@ def run(
entrypoint = obj.architype
else:
print(f"Entrypoint {node} not found.")
Jac.close_context()
return

# TODO: handle no override name
Expand All @@ -139,7 +140,7 @@ def run(
else:
print(f"Walker {walker} not found.")

jctx.close()
Jac.close_context()


@cmd_registry.register
Expand All @@ -148,7 +149,7 @@ def get_object(id: str, session: str = "") -> dict:
if session == "":
session = cmd_registry.args.session if "session" in cmd_registry.args else ""

jctx = Jac.new_context(session=session)
jctx = Jac.create_context(session=session)

data = {}
if id == "root":
Expand All @@ -158,7 +159,7 @@ def get_object(id: str, session: str = "") -> dict:
else:
print(f"Object with id {id} not found.")

jctx.close()
Jac.close_context()
return data


Expand Down Expand Up @@ -209,26 +210,43 @@ def lsp() -> None:


@cmd_registry.register
def enter(filename: str, entrypoint: str, args: list) -> None:
"""Run the specified entrypoint function in the given .jac file.
def enter(
filename: str,
entrypoint: str,
args: list,
session: str = "",
root: str = "",
node: str = "",
) -> None:
"""
Run the specified entrypoint function in the given .jac file.
:param filename: The path to the .jac file.
:param entrypoint: The name of the entrypoint function.
:param args: Arguments to pass to the entrypoint function.
:param session: shelve.Shelf file path.
:param root: root executor.
:param node: starting node.
"""
jctx = Jac.create_context(session=session, root=root, entry=node)

if filename.endswith(".jac"):
base, mod_name = os.path.split(filename)
base = base if base else "./"
mod_name = mod_name[:-4]
(mod,) = jac_import(target=mod_name, base_path=base)
if not mod:
print("Errors occurred while importing the module.")
return
else:
getattr(mod, entrypoint)(*args)
architype = getattr(mod, entrypoint)(*args)
if isinstance(architype, WalkerArchitype):
Jac.spawn_call(jctx.entry.architype, architype)

else:
print("Not a .jac file.")

Jac.close_context()


@cmd_registry.register
def test(
Expand All @@ -250,7 +268,7 @@ def test(
jac test => jac test -d .
"""
jctx = Jac.new_context()
Jac.create_context()

failcount = Jac.run_test(
filepath=filepath,
Expand All @@ -261,7 +279,7 @@ def test(
verbose=verbose,
)

jctx.close()
Jac.close_context()

if failcount:
raise SystemExit(f"Tests failed: {failcount}")
Expand Down Expand Up @@ -365,7 +383,7 @@ def dot(
base = base if base else "./"
mod = mod[:-4]

jctx = Jac.new_context(base_path=base, session=session)
Jac.create_context(base_path=base, session=session)

if filename.endswith(".jac"):
jac_import(
Expand All @@ -390,7 +408,7 @@ def dot(
import traceback

traceback.print_exc()
jctx.close()
Jac.close_context()
return
file_name = saveto if saveto else f"{mod}.dot"
with open(file_name, "w") as file:
Expand All @@ -399,7 +417,7 @@ def dot(
else:
print("Not a .jac file.")

jctx.close()
Jac.close_context()


@cmd_registry.register
Expand Down
7 changes: 3 additions & 4 deletions jaclang/compiler/passes/main/tests/test_pyast_gen_pass.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import jaclang.compiler.absyntree as ast
from jaclang.compiler.compile import jac_file_to_pass
from jaclang.compiler.passes.main import PyastGenPass, SubNodeTabPass
from jaclang.plugin.feature import JacFeature as Jac
from jaclang.utils.test import AstSyncTestMixin, TestCaseMicroSuite


Expand All @@ -29,10 +30,6 @@ class PyastGenPassTests(TestCaseMicroSuite, AstSyncTestMixin):

TargetPass = PyastGenPass

def setUp(self) -> None:
"""Set up test."""
return super().setUp()

def test_hodge_podge(self) -> None:
"""Basic test for pass."""
code_gen = jac_file_to_pass(
Expand All @@ -53,6 +50,7 @@ def test_circle_py_ast(self) -> None:
if code_gen.ir.gen.py_ast and isinstance(
code_gen.ir.gen.py_ast[0], ast3.Module
):
Jac.create_context()
prog = compile(code_gen.ir.gen.py_ast[0], filename="<ast>", mode="exec")
captured_output = io.StringIO()
sys.stdout = captured_output
Expand All @@ -70,6 +68,7 @@ def test_circle_py_ast(self) -> None:
"Area of a Circle with radius 5 using class: 78",
stdout_value,
)
Jac.close_context()

self.assertFalse(code_gen.errors_had)

Expand Down
11 changes: 4 additions & 7 deletions jaclang/compiler/tests/test_importer.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,23 +12,20 @@
class TestLoader(TestCase):
"""Test Jac self.prse."""

def setUp(self) -> None:
"""Set up test."""
Jac.new_context()
return super().setUp()

def test_import_basic_python(self) -> None:
"""Test basic self loading."""
Jac.new_context(base_path=self.fixture_abs_path(__file__))
Jac.create_context(base_path=self.fixture_abs_path(__file__))
(h,) = jac_import("fixtures.hello_world", base_path=__file__)
self.assertEqual(h.hello(), "Hello World!") # type: ignore
Jac.close_context()

def test_modules_correct(self) -> None:
"""Test basic self loading."""
Jac.new_context(base_path=self.fixture_abs_path(__file__))
Jac.create_context(base_path=self.fixture_abs_path(__file__))
jac_import("fixtures.hello_world", base_path=__file__)
self.assertIn("module 'fixtures.hello_world'", str(sys.modules))
self.assertIn("/tests/fixtures/hello_world.jac", str(sys.modules))
Jac.close_context()

def test_jac_py_import(self) -> None:
"""Basic test for pass."""
Expand Down
16 changes: 11 additions & 5 deletions jaclang/plugin/default.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ class JacFeatureDefaults:

@staticmethod
@hookimpl
def new_context(
def create_context(
base_path: str,
session: Optional[str],
root: Optional[str],
Expand All @@ -79,13 +79,19 @@ def new_context(

@staticmethod
@hookimpl
def current_context() -> ExecutionContext:
def get_context() -> ExecutionContext:
"""Get current execution context."""
return ExecutionContext.get()

@staticmethod
@hookimpl
def current_context_datasource() -> Memory:
def close_context() -> None:
"""Close current execution context."""
ExecutionContext.close()

@staticmethod
@hookimpl
def get_datasource() -> Memory:
"""Get current execution context."""
return ExecutionContext.get().datasource

Expand Down Expand Up @@ -260,7 +266,7 @@ def jac_import(
lng,
items,
)
jctx = Jac.current_context()
jctx = Jac.get_context()
if lng == "py":
import_result = PythonImporter(jctx.jac_machine).run_import(spec)
else:
Expand Down Expand Up @@ -539,7 +545,7 @@ def assign_compr(
@hookimpl
def get_root() -> Root:
"""Jac's assign comprehension feature."""
return cast(Root, Jac.current_context().root.architype)
return cast(Root, Jac.get_context().root.architype)

@staticmethod
@hookimpl
Expand Down
17 changes: 11 additions & 6 deletions jaclang/plugin/feature.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,26 +42,31 @@ class JacFeature:
Walker: TypeAlias = WalkerArchitype

@staticmethod
def new_context(
def create_context(
base_path: str = "",
session: Optional[str] = None,
root: Optional[str] = None,
entry: Optional[str] = None,
) -> ExecutionContext:
"""Create new execution context."""
return pm.hook.new_context(
return pm.hook.create_context(
base_path=base_path, session=session, root=root, entry=entry
)

@staticmethod
def current_context() -> ExecutionContext:
def get_context() -> ExecutionContext:
"""Get current execution context."""
return pm.hook.current_context()
return pm.hook.get_context()

@staticmethod
def current_context_datasource() -> Memory:
def close_context() -> None:
"""Get current execution context."""
return pm.hook.current_context_datasource()
pm.hook.close_context()

@staticmethod
def get_datasource() -> Memory:
"""Get current execution context."""
return pm.hook.get_datasource()

@staticmethod
def make_architype(
Expand Down
12 changes: 9 additions & 3 deletions jaclang/plugin/spec.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ class JacFeatureSpec:

@staticmethod
@hookspec(firstresult=True)
def new_context(
def create_context(
base_path: str,
session: Optional[str],
root: Optional[str],
Expand All @@ -56,13 +56,19 @@ def new_context(

@staticmethod
@hookspec(firstresult=True)
def current_context() -> ExecutionContext:
def get_context() -> ExecutionContext:
"""Get current execution context."""
raise NotImplementedError

@staticmethod
@hookspec(firstresult=True)
def current_context_datasource() -> Memory:
def close_context() -> None:
"""Get current execution context."""
raise NotImplementedError

@staticmethod
@hookspec(firstresult=True)
def get_datasource() -> Memory:
"""Get current execution context datasource."""
raise NotImplementedError

Expand Down
18 changes: 9 additions & 9 deletions jaclang/runtimelib/architype.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@


@dataclass
class Report:
class AnchorReport:
"""Report Handler."""

id: str
Expand All @@ -37,13 +37,13 @@ def save(self) -> None:
from jaclang.plugin.feature import JacFeature as Jac

self.persistent = True
Jac.current_context_datasource().set(self.id, self)
Jac.get_datasource().set(self.id, self)

def destroy(self) -> None:
"""Destroy Anchor."""
from jaclang.plugin.feature import JacFeature as Jac

Jac.current_context_datasource().remove(self.id)
Jac.get_datasource().remove(self.id)

def unlinked_architype(self) -> Architype | None:
"""Unlink architype."""
Expand All @@ -69,9 +69,9 @@ def __setstate__(self, state: dict[str, Any]) -> None:
self.architype.__jac__ = self
self.hash = hash(dumps(self))

def report(self) -> Report:
def report(self) -> AnchorReport:
"""Report Anchor."""
return Report(
return AnchorReport(
id=self.id.hex,
context=(
asdict(self.architype)
Expand Down Expand Up @@ -109,7 +109,7 @@ def populate_edges(self) -> None:
from jaclang.plugin.feature import JacFeature as Jac

if self.edge_ids:
jsrc = Jac.current_context_datasource()
jsrc = Jac.get_datasource()

edges = [
edge for e_id in self.edge_ids if (edge := jsrc.find_by_id(e_id))
Expand Down Expand Up @@ -224,7 +224,7 @@ def destroy(self) -> None:
for edge in self.edges:
edge.destroy()

Jac.current_context_datasource().remove(self.id)
Jac.get_datasource().remove(self.id)

def __getstate__(self) -> dict[str, object]:
"""Serialize Node Anchor."""
Expand Down Expand Up @@ -254,7 +254,7 @@ def populate_nodes(self) -> None:
"""Populate nodes for the edges from node ids."""
from jaclang.plugin.feature import JacFeature as Jac

jsrc = Jac.current_context_datasource()
jsrc = Jac.get_datasource()

if self.source_id:
self.source = jsrc.find_by_id(self.source_id)
Expand Down Expand Up @@ -295,7 +295,7 @@ def destroy(self) -> None:

self.populate_nodes()
self.detach()
Jac.current_context_datasource().remove(self.id)
Jac.get_datasource().remove(self.id)

def __getstate__(self) -> dict[str, object]:
"""Serialize Node Anchor."""
Expand Down
Loading

0 comments on commit 861512f

Please sign in to comment.