astreum 0.1.1__tar.gz → 0.1.2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of astreum might be problematic. Click here for more details.

@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: astreum
3
- Version: 0.1.1
3
+ Version: 0.1.2
4
4
  Summary: Python library to interact with the Astreum blockchain and its Lispeum virtual machine.
5
5
  Author-email: "Roy R. O. Okello" <roy@stelar.xyz>
6
6
  Project-URL: Homepage, https://github.com/astreum/lib
@@ -13,4 +13,12 @@ Description-Content-Type: text/markdown
13
13
  License-File: LICENSE
14
14
 
15
15
  # lib
16
+
16
17
  Python library to interact with the Astreum blockchain and its Lispeum virtual machine.
18
+
19
+ [View on PyPI](https://pypi.org/project/astreum/)
20
+
21
+ ## Testing
22
+
23
+ python -m unittest discover -s tests
24
+
@@ -0,0 +1,10 @@
1
+ # lib
2
+
3
+ Python library to interact with the Astreum blockchain and its Lispeum virtual machine.
4
+
5
+ [View on PyPI](https://pypi.org/project/astreum/)
6
+
7
+ ## Testing
8
+
9
+ python -m unittest discover -s tests
10
+
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "astreum"
3
- version = "0.1.1"
3
+ version = "0.1.2"
4
4
  authors = [
5
5
  { name="Roy R. O. Okello", email="roy@stelar.xyz" },
6
6
  ]
@@ -0,0 +1,163 @@
1
+ import threading
2
+ from typing import Callable, Dict, List, Optional, Tuple
3
+ import uuid
4
+
5
+ from src.astreum.machine.environment import Environment
6
+ from src.astreum.machine.expression import Expr
7
+ from src.astreum.machine.tokenizer import tokenize
8
+ from src.astreum.machine.parser import parse
9
+
10
+ class AstreumMachine:
11
+ def __init__(self):
12
+ # Initialize the global environment
13
+ self.global_env = Environment()
14
+
15
+ # Dictionary to manage user sessions: session_id -> local Environment
16
+ self.sessions: Dict[str, Environment] = {}
17
+
18
+ # Lock for thread-safe access to the global environment and sessions
19
+ self.lock = threading.Lock()
20
+
21
+ def create_session(self) -> str:
22
+ """
23
+ Create a new user session with a unique session ID and a fresh local environment.
24
+ Returns the session ID.
25
+ """
26
+ session_id = str(uuid.uuid4())
27
+ with self.lock:
28
+ self.sessions[session_id] = Environment(parent=self.global_env)
29
+ return session_id
30
+
31
+ def terminate_session(self, session_id: str) -> bool:
32
+ """
33
+ Terminate an existing user session.
34
+ Returns True if the session was successfully terminated, False otherwise.
35
+ """
36
+ with self.lock:
37
+ if session_id in self.sessions:
38
+ del self.sessions[session_id]
39
+ return True
40
+ else:
41
+ return False
42
+
43
+ def get_session_env(self, session_id: str) -> Optional[Environment]:
44
+ """
45
+ Retrieve the local environment for a given session ID.
46
+ Returns the Environment if found, None otherwise.
47
+ """
48
+ with self.lock:
49
+ return self.sessions.get(session_id, None)
50
+
51
+ def evaluate_code(self, code: str, session_id: str) -> Tuple[Optional[Expr], Optional[str]]:
52
+ """
53
+ Evaluate code within the context of a user's session.
54
+ Returns a tuple of (Result Expression, Error Message).
55
+ If evaluation is successful, Error Message is None.
56
+ If an error occurs, Result Expression is None.
57
+ """
58
+ env = self.get_session_env(session_id)
59
+ if env is None:
60
+ return None, f"Session ID {session_id} not found."
61
+
62
+ try:
63
+ tkns = tokenize(input=code)
64
+ expr, _ = parse(tokens=tkns)
65
+ result = self.evaluate(expr, env)
66
+ return result, None
67
+ except Exception as e:
68
+ return None, str(e)
69
+
70
+ def evaluate(self, expr: Expr, env: Environment) -> Expr:
71
+
72
+ if isinstance(expr, Expr.Integer):
73
+ return expr
74
+ elif isinstance(expr, Expr.String):
75
+ return expr
76
+ elif isinstance(expr, Expr.Symbol):
77
+ value = env.get(expr.value)
78
+ if value is not None:
79
+ return value
80
+ else:
81
+ # Return the symbol itself if not found in the environment
82
+ return expr
83
+ elif isinstance(expr, Expr.ListExpr):
84
+ if not expr.elements:
85
+ raise ValueError("Empty list cannot be evaluated")
86
+
87
+ first = expr.elements[0]
88
+ if isinstance(first, Expr.Symbol):
89
+ # Check if it's a user-defined function
90
+ user_def_fn = env.get(first.value)
91
+ if isinstance(user_def_fn, Expr.Function):
92
+ fn_params, fn_body = user_def_fn.params, user_def_fn.body
93
+ args = expr.elements[1:]
94
+
95
+ if len(fn_params) != len(args):
96
+ raise TypeError(f"expected {len(fn_params)} arguments, got {len(args)}")
97
+
98
+ # Create a new environment for the function execution, inheriting from the function's defining environment
99
+ new_env = Environment(parent=env)
100
+
101
+ # Evaluate and bind each argument
102
+ for param, arg in zip(fn_params, args):
103
+ evaluated_arg = self.evaluate(arg, env)
104
+ new_env.set(param, evaluated_arg)
105
+
106
+ # Evaluate the function body within the new environment
107
+ return self.evaluate(fn_body, new_env)
108
+
109
+ # Check for special functions
110
+ elif first.value in ["def", "+"]:
111
+ args = expr.elements[1:]
112
+
113
+ match first.value:
114
+ case "def":
115
+ if len(args) != 2:
116
+ raise TypeError("def expects exactly two arguments: a symbol and an expression")
117
+ if not isinstance(args[0], Expr.Symbol):
118
+ raise TypeError("First argument to def must be a symbol")
119
+
120
+ var_name = args[0].value
121
+ var_value = self.evaluate(args[1], env)
122
+ env.set(var_name, var_value)
123
+ return args[0] # Return the symbol name
124
+
125
+ case "+":
126
+ # Ensure all arguments are integers
127
+ evaluated_args = [self.evaluate(arg, env) for arg in args]
128
+ if not all(isinstance(arg, Expr.Integer) for arg in evaluated_args):
129
+ raise TypeError("All arguments to + must be integers")
130
+
131
+ # Sum the integer values and return as an Expr.Integer
132
+ result = sum(arg.value for arg in evaluated_args)
133
+ return Expr.Integer(result)
134
+
135
+ else:
136
+ # Attempt to evaluate as a function application
137
+ func = self.evaluate(first, env)
138
+ if isinstance(func, Expr.Function):
139
+ fn_params, fn_body = func.params, func.body
140
+ args = expr.elements[1:]
141
+
142
+ if len(fn_params) != len(args):
143
+ raise TypeError(f"expected {len(fn_params)} arguments, got {len(args)}")
144
+
145
+ # Create a new environment for the function execution, inheriting from the function's defining environment
146
+ new_env = Environment(parent=func.env)
147
+
148
+ # Evaluate and bind each argument
149
+ for param, arg in zip(fn_params, args):
150
+ evaluated_arg = self.evaluate(arg, env)
151
+ new_env.set(param, evaluated_arg)
152
+
153
+ # Evaluate the function body within the new environment
154
+ return self.evaluate(fn_body, new_env)
155
+ else:
156
+ raise TypeError(f"'{first.value}' is not a function")
157
+ else:
158
+ evaluated_elements = [self.evaluate(e, env) for e in expr.elements]
159
+ return Expr.ListExpr(evaluated_elements)
160
+ elif isinstance(expr, Expr.Function):
161
+ return expr
162
+ else:
163
+ raise TypeError(f"Unknown expression type: {type(expr)}")
@@ -0,0 +1,25 @@
1
+ # Define the Environment class
2
+ from typing import Callable, Dict, List, Optional
3
+ from src.astreum.machine.expression import Expr
4
+
5
+
6
+ class Environment:
7
+ def __init__(self, parent: 'Environment' = None):
8
+ self.data: Dict[str, Expr] = {}
9
+ self.parent = parent
10
+
11
+ def set(self, name: str, value: Expr):
12
+ """Set a variable in the current environment."""
13
+ self.data[name] = value
14
+
15
+ def get(self, name: str) -> Optional[Expr]:
16
+ """Retrieve a variable's value, searching parent environments if necessary."""
17
+ if name in self.data:
18
+ return self.data[name]
19
+ elif self.parent:
20
+ return self.parent.get(name)
21
+ else:
22
+ return None
23
+
24
+ def __repr__(self):
25
+ return f"Environment({self.data})"
@@ -0,0 +1,2 @@
1
+ class ParseError(Exception):
2
+ pass
@@ -0,0 +1,50 @@
1
+ from typing import List
2
+
3
+ class Expr:
4
+ class ListExpr:
5
+ def __init__(self, elements: List['Expr']):
6
+ self.elements = elements
7
+
8
+ @property
9
+ def value(self):
10
+ inner = " ".join(str(e) for e in self.elements)
11
+ return f"({inner})"
12
+
13
+
14
+ def __repr__(self):
15
+ if not self.elements:
16
+ return "()"
17
+
18
+ inner = " ".join(str(e) for e in self.elements)
19
+ return f"({inner})"
20
+
21
+ class Symbol:
22
+ def __init__(self, value: str):
23
+ self.value = value
24
+
25
+ def __repr__(self):
26
+ return self.value
27
+
28
+ class Integer:
29
+ def __init__(self, value: int):
30
+ self.value = value
31
+
32
+ def __repr__(self):
33
+ return str(self.value)
34
+
35
+ class String:
36
+ def __init__(self, value: str):
37
+ self.value = value
38
+
39
+ def __repr__(self):
40
+ return f'"{self.value}"'
41
+
42
+ class Function:
43
+ def __init__(self, params: List[str], body: 'Expr'):
44
+ self.params = params
45
+ self.body = body
46
+
47
+ def __repr__(self):
48
+ params_str = " ".join(self.params)
49
+ body_str = str(self.body)
50
+ return f"(fn ({params_str}) {body_str})"
@@ -0,0 +1,44 @@
1
+ # Parser function
2
+ from typing import List, Tuple
3
+ from src.astreum.machine.error import ParseError
4
+ from src.astreum.machine.expression import Expr
5
+
6
+
7
+ def parse(tokens: List[str]) -> Tuple[Expr, List[str]]:
8
+ if not tokens:
9
+ raise ParseError("Unexpected end of input")
10
+
11
+ first_token, *rest = tokens
12
+
13
+ if first_token == '(':
14
+ if not rest:
15
+ raise ParseError("Expected token after '('")
16
+
17
+ list_items = []
18
+ inner_tokens = rest
19
+
20
+ while inner_tokens:
21
+ if inner_tokens[0] == ')':
22
+ # End of list
23
+ return Expr.ListExpr(list_items), inner_tokens[1:]
24
+
25
+ expr, inner_tokens = parse(inner_tokens)
26
+ list_items.append(expr)
27
+
28
+ raise ParseError("Expected closing ')'")
29
+
30
+ elif first_token == ')':
31
+ raise ParseError("Unexpected closing parenthesis")
32
+
33
+ elif first_token.startswith('"') and first_token.endswith('"'):
34
+ string_content = first_token[1:-1]
35
+ return Expr.String(string_content), rest
36
+
37
+ else:
38
+ # Try to parse as integer
39
+ try:
40
+ number = int(first_token)
41
+ return Expr.Integer(number), rest
42
+ except ValueError:
43
+ # Treat as symbol
44
+ return Expr.Symbol(first_token), rest
@@ -0,0 +1,52 @@
1
+
2
+
3
+ # Tokenizer function
4
+ from typing import List
5
+
6
+ from src.astreum.machine.error import ParseError
7
+
8
+
9
+ def tokenize(input: str) -> List[str]:
10
+ tokens = []
11
+ current_token = ""
12
+ in_string = False
13
+ escape = False
14
+
15
+ for char in input:
16
+ if in_string:
17
+ if escape:
18
+ current_token += char
19
+ escape = False
20
+ elif char == '\\':
21
+ escape = True
22
+ elif char == '"':
23
+ in_string = False
24
+ tokens.append(f'"{current_token}"')
25
+ current_token = ""
26
+ else:
27
+ current_token += char
28
+ else:
29
+ if char.isspace():
30
+ if current_token:
31
+ tokens.append(current_token)
32
+ current_token = ""
33
+ elif char == '(' or char == ')':
34
+ if current_token:
35
+ tokens.append(current_token)
36
+ current_token = ""
37
+ tokens.append(char)
38
+ elif char == '"':
39
+ if current_token:
40
+ tokens.append(current_token)
41
+ current_token = ""
42
+ in_string = True
43
+ else:
44
+ current_token += char
45
+
46
+ if in_string:
47
+ raise ParseError("Unterminated string literal")
48
+
49
+ if current_token:
50
+ tokens.append(current_token)
51
+
52
+ return tokens
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: astreum
3
- Version: 0.1.1
3
+ Version: 0.1.2
4
4
  Summary: Python library to interact with the Astreum blockchain and its Lispeum virtual machine.
5
5
  Author-email: "Roy R. O. Okello" <roy@stelar.xyz>
6
6
  Project-URL: Homepage, https://github.com/astreum/lib
@@ -13,4 +13,12 @@ Description-Content-Type: text/markdown
13
13
  License-File: LICENSE
14
14
 
15
15
  # lib
16
+
16
17
  Python library to interact with the Astreum blockchain and its Lispeum virtual machine.
18
+
19
+ [View on PyPI](https://pypi.org/project/astreum/)
20
+
21
+ ## Testing
22
+
23
+ python -m unittest discover -s tests
24
+
@@ -0,0 +1,14 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/astreum/__init__.py
5
+ src/astreum.egg-info/PKG-INFO
6
+ src/astreum.egg-info/SOURCES.txt
7
+ src/astreum.egg-info/dependency_links.txt
8
+ src/astreum.egg-info/top_level.txt
9
+ src/astreum/machine/__init__.py
10
+ src/astreum/machine/environment.py
11
+ src/astreum/machine/error.py
12
+ src/astreum/machine/expression.py
13
+ src/astreum/machine/parser.py
14
+ src/astreum/machine/tokenizer.py
astreum-0.1.1/README.md DELETED
@@ -1,2 +0,0 @@
1
- # lib
2
- Python library to interact with the Astreum blockchain and its Lispeum virtual machine.
@@ -1,10 +0,0 @@
1
- class AstreumMachine:
2
- def __init__(self):
3
- pass
4
-
5
- def evaluate(self, code: str) -> list[str]:
6
- return self.tokenize(code)
7
-
8
- def tokenize(self, input: str) -> list[str]:
9
- tokens = input.replace("(", " ( ").replace(")", " ) ").split()
10
- return tokens
@@ -1,9 +0,0 @@
1
- LICENSE
2
- README.md
3
- pyproject.toml
4
- src/astreum/__init__.py
5
- src/astreum/machine.py
6
- src/astreum.egg-info/PKG-INFO
7
- src/astreum.egg-info/SOURCES.txt
8
- src/astreum.egg-info/dependency_links.txt
9
- src/astreum.egg-info/top_level.txt
File without changes
File without changes
File without changes