Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Contexts[string] form #1247

Merged
merged 4 commits into from
Dec 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion mathics/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@

version_info[package] = package_version

version_string = """Mathics {mathics}
version_string = """Mathics3 {mathics}
on {python}
using SymPy {sympy}, mpmath {mpmath}, numpy {numpy}""".format(
**version_info
Expand Down
35 changes: 25 additions & 10 deletions mathics/builtin/scoping.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
from mathics.core.evaluation import Evaluation
from mathics.core.list import ListExpression
from mathics.core.symbols import Symbol, fully_qualified_symbol_name
from mathics.eval.scoping import eval_contexts, eval_contexts_with_string


def get_scoping_vars(var_list, msg_symbol="", evaluation=None):
Expand Down Expand Up @@ -232,24 +233,38 @@ class Contexts(Builtin):

<dl>
<dt>'Contexts[]'
<dd>yields a list of all contexts.
<dd>returns a list of contexts.
<dt>'Contexts["string"]'
<dd>returns a list of contexts that match the string.
</dl>

## this assignment makes sure that a definition in Global` exists
## >> x = 5;
## X> Contexts[] // InputForm
'Contexts' allows the string patterns with the follwing metacharacters:
<ul>
<li> '*' zero or more characters
<li> '@' one or more characters, excluding uppercase letters
</ul>

Get a list of all contexts:
>> Contexts[]
= ...

Get a list of HTML contexts only:
>> Contexts["HTML*"]
= {HTML`, HTML`Parser`}
"""

summary_text = "list all the defined contexts"
summary_text = "list defined contexts"

def eval(self, evaluation: Evaluation):
def eval(self, evaluation: Evaluation) -> ListExpression:
"Contexts[]"

contexts = set()
for name in evaluation.definitions.get_names():
contexts.add(String(name[: name.rindex("`") + 1]))
return eval_contexts(evaluation.definitions)

return ListExpression(*sorted(contexts))
def eval_with_string(self, string, evaluation: Evaluation) -> ListExpression:
"Contexts[string_]"
if not isinstance(string, String):
return ListExpression()
return eval_contexts_with_string(string.value, evaluation.definitions)


class ContextPath_(Predefined):
Expand Down
41 changes: 7 additions & 34 deletions mathics/builtin/system.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
import subprocess
import sys

from pympler.asizeof import asizeof

from mathics import version_string
from mathics.core.atoms import Integer, Integer0, IntegerM1, Real, String
from mathics.core.attributes import A_CONSTANT
Expand Down Expand Up @@ -383,41 +385,12 @@ class MemoryInUse(Builtin):
= ...
"""

summary_text = "number of bytes of memory currently being used by Mathics"
summary_text = "number of bytes of memory currently being used by Mathics3"

def eval_0(self, evaluation) -> Integer:
def eval(self, evaluation: Evaluation) -> Integer:
"""MemoryInUse[]"""
# Partially borrowed from https://code.activestate.com/recipes/577504/
from itertools import chain
from sys import getsizeof

definitions = evaluation.definitions
seen = set()
try:
default_size = getsizeof(0)
except TypeError:
return IntegerM1

handlers = {
tuple: iter,
list: iter,
dict: (lambda d: chain.from_iterable(d.items())),
set: iter,
frozenset: iter,
}

def sizeof(obj):
if id(obj) in seen:
return 0
seen.add(id(obj))
s = getsizeof(obj, default_size)
for typ, handler in handlers.items():
if isinstance(obj, typ):
s += sum(map(sizeof, handler(obj)))
break
return s

return Integer(sizeof(definitions))
gc.collect()
return Integer(asizeof(evaluation.definitions))


class Packages(Predefined):
Expand Down Expand Up @@ -794,7 +767,7 @@ class Version(Predefined):
</dl>

>> $Version
= Mathics ...
= Mathics3 ...
"""

summary_text = "the current Mathics version"
Expand Down
5 changes: 3 additions & 2 deletions mathics/core/definitions.py
Original file line number Diff line number Diff line change
Expand Up @@ -280,7 +280,7 @@ def get_names(self):
| self.get_user_names()
)

def get_accessible_contexts(self):
def get_accessible_contexts(self) -> set:
"""Return the contexts reachable though $Context or $ContextPath."""
accessible_ctxts = set(ctx for ctx in self.context_path)
accessible_ctxts.add(self.current_context)
Expand Down Expand Up @@ -558,7 +558,8 @@ def mark_changed(self, definition: "Definition") -> None:
def reset_user_definition(self, name) -> None:
assert not isinstance(name, Symbol)
fullname = self.lookup_name(name)
del self.user[fullname]
if fullname in self.user:
del self.user[fullname]
self.clear_cache(fullname)
# TODO fix changed

Expand Down
37 changes: 37 additions & 0 deletions mathics/eval/scoping.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,12 @@
"""
Evaluation module corresponding to builtin functions in mathics.builtins.scoping.
"""
import re

from mathics.core.atoms import String
from mathics.core.definitions import Definitions
from mathics.core.evaluation import Evaluation
from mathics.core.list import ListExpression
from mathics.core.symbols import Symbol, fully_qualified_symbol_name


Expand All @@ -25,6 +33,35 @@ def dynamic_scoping(func, vars, evaluation: Evaluation):
return result


def eval_contexts(definitions: Definitions) -> ListExpression:
"""
Corresponding eval routine (sans builtin class boilerplate) for Context[]
"""
return ListExpression(*sorted(get_contexts(definitions)))


def eval_contexts_with_string(string: str, definitions: Definitions) -> ListExpression:
"""
Corresponding eval routine (sans builtin class boilerplate) for Context[string]
"""
contexts = [context.value for context in get_contexts(definitions)]

short_pattern = (
string.replace("@", "[^A-Z]+").replace("*", ".*").replace("$", r"\$")
)
regex = re.compile("^" + short_pattern + "`$")

matched_contexts = [String(name) for name in contexts if regex.match(name)]
return ListExpression(*sorted(matched_contexts))


def get_contexts(definitions) -> set:
contexts = set()
for name in definitions.get_names():
contexts.add(String(name[: name.rindex("`") + 1]))
return contexts


def get_scoping_vars(var_list, msg_symbol="", evaluation=None):
def message(tag, *args):
if msg_symbol and evaluation:
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ dependencies = [
"pillow >= 9.2",
"pint",
"python-dateutil",
# Pympler is used onlyfor ByteCount[]. It could be made optional.
# Pympler is used in ByteCount[] and MemoryInUse[].
"Pympler",
"requests",
"scipy",
Expand Down
Loading