Compare commits
No commits in common. "9f467fa2234e94e2dc9618bb752437da8a75471e" and "cf2d82acc6fecfd85f08162920835cce3502f987" have entirely different histories.
9f467fa223
...
cf2d82acc6
1
.vscode/settings.json
vendored
1
.vscode/settings.json
vendored
@ -1,7 +1,6 @@
|
|||||||
{
|
{
|
||||||
"cSpell.words": [
|
"cSpell.words": [
|
||||||
"autochurch",
|
"autochurch",
|
||||||
"clearmacros",
|
|
||||||
"Endnodes",
|
"Endnodes",
|
||||||
"freevar",
|
"freevar",
|
||||||
"mdel",
|
"mdel",
|
||||||
|
27
README.md
27
README.md
@ -19,7 +19,6 @@
|
|||||||
|
|
||||||
## Usage
|
## Usage
|
||||||
|
|
||||||
|
|
||||||
Type lambda expressions into the prompt, and Lamb will evaluate them. \
|
Type lambda expressions into the prompt, and Lamb will evaluate them. \
|
||||||
Use your `\` (backslash) key to type a `λ`. \
|
Use your `\` (backslash) key to type a `λ`. \
|
||||||
To define macros, use `=`. For example,
|
To define macros, use `=`. For example,
|
||||||
@ -31,30 +30,22 @@ To define macros, use `=`. For example,
|
|||||||
|
|
||||||
Note that there are spaces in `λa.a F T`. With no spaces, `aFT` will be parsed as one variable. \
|
Note that there are spaces in `λa.a F T`. With no spaces, `aFT` will be parsed as one variable. \
|
||||||
Lambda functions can only take single-letter, lowercase arguments. `λA.A` is not valid syntax. \
|
Lambda functions can only take single-letter, lowercase arguments. `λA.A` is not valid syntax. \
|
||||||
Free variables will be shown with a `'`, like `a'`.
|
Unbound variables (upper and lower case) that aren't macros will become free variables. Free variables will be shown with a `'`, like `a'`.
|
||||||
|
|
||||||
Macros are case-sensitive. If you define a macro `MAC` and accidentally write `mac` in the prompt, `mac` will become a free variable.
|
Be careful, macros are case-sensitive. If you define a macro `MAC` and accidentally write `mac` in the prompt, `mac` will become a free variable.
|
||||||
|
|
||||||
Numbers will automatically be converted to Church numerals. For example, the following line will reduce to `T`.
|
Numbers will automatically be converted to Church numerals. For example, the following line will reduce to `T`.
|
||||||
```
|
```
|
||||||
==> 3 NOT F
|
==> 3 NOT F
|
||||||
```
|
```
|
||||||
|
|
||||||
If an expression takes too long to evaluate, you may interrupt reduction with `Ctrl-C`. \
|
If an expression takes too long to evaluate, you may interrupt reduction with `Ctrl-C`.
|
||||||
Exit the prompt with `Ctrl-C` or `Ctrl-D`.
|
|
||||||
|
|
||||||
There are many useful macros in [macros.lamb](./macros.lamb). Load them with the `:load` command:
|
|
||||||
```
|
|
||||||
==> :load macros.lamb
|
|
||||||
```
|
|
||||||
|
|
||||||
Have fun!
|
|
||||||
|
|
||||||
-------------------------------------------------
|
-------------------------------------------------
|
||||||
|
|
||||||
## Commands
|
## Commands
|
||||||
|
|
||||||
Lamb understands many commands. Prefix them with a `:` in the prompt.
|
Lamb comes with a few commands. Prefix them with a `:`
|
||||||
|
|
||||||
`:help` Prints a help message
|
`:help` Prints a help message
|
||||||
|
|
||||||
@ -66,12 +57,8 @@ Lamb understands many commands. Prefix them with a `:` in the prompt.
|
|||||||
|
|
||||||
`:mdel [macro]` Delete a macro
|
`:mdel [macro]` Delete a macro
|
||||||
|
|
||||||
`:clearmacros` Delete all macros
|
`:save [filename]`\
|
||||||
|
`:load [filename]` Save or load the current environment to a file. The lines in a file look exactly the same as regular entries in the prompt, but must only contain macro definitions.
|
||||||
`:save [filename]` \
|
|
||||||
`:load [filename]` \
|
|
||||||
Save or load macros from a file.
|
|
||||||
The lines in a file look exactly the same as regular entries in the prompt, but can only contain macro definitions. See [macros.lamb](./macros.lamb) for an example.
|
|
||||||
|
|
||||||
-------------------------------------------------
|
-------------------------------------------------
|
||||||
|
|
||||||
@ -88,11 +75,13 @@ Lamb treats each λ expression as a binary tree. Variable binding and reduction
|
|||||||
|
|
||||||
|
|
||||||
## Todo (pre-release, in this order):
|
## Todo (pre-release, in this order):
|
||||||
|
- Fix :save
|
||||||
- Cleanup warnings
|
- Cleanup warnings
|
||||||
- Truncate long expressions in warnings
|
- Truncate long expressions in warnings
|
||||||
- Prevent macro-chaining recursion
|
- Prevent macro-chaining recursion
|
||||||
- Full-reduce option (expand all macros)
|
- Full-reduce option (expand all macros)
|
||||||
- step-by-step reduction
|
- step-by-step reduction
|
||||||
|
- Cleanup files
|
||||||
- Update screenshot
|
- Update screenshot
|
||||||
- Update documentation & "internals" section.
|
- Update documentation & "internals" section.
|
||||||
- PyPi package
|
- PyPi package
|
||||||
|
@ -1,6 +1,7 @@
|
|||||||
from . import utils
|
from . import utils
|
||||||
from . import nodes
|
from . import node
|
||||||
from . import parser
|
from . import parser
|
||||||
|
from . import commands
|
||||||
|
|
||||||
from .runner import Runner
|
from .runner import Runner
|
||||||
from .runner import StopReason
|
from .runner import StopReason
|
@ -1,29 +1,66 @@
|
|||||||
if __name__ != "__main__":
|
|
||||||
raise ImportError("lamb.__main__ should never be imported. Run it directly.")
|
|
||||||
|
|
||||||
from prompt_toolkit import PromptSession
|
from prompt_toolkit import PromptSession
|
||||||
|
from prompt_toolkit.completion import WordCompleter
|
||||||
from prompt_toolkit import print_formatted_text as printf
|
from prompt_toolkit import print_formatted_text as printf
|
||||||
from prompt_toolkit.formatted_text import FormattedText
|
from prompt_toolkit.formatted_text import FormattedText
|
||||||
from prompt_toolkit.formatted_text import to_plain_text
|
from prompt_toolkit.formatted_text import to_plain_text
|
||||||
|
from prompt_toolkit.key_binding import KeyBindings
|
||||||
|
from prompt_toolkit.lexers import Lexer
|
||||||
from pyparsing import exceptions as ppx
|
from pyparsing import exceptions as ppx
|
||||||
|
|
||||||
import lamb
|
import lamb
|
||||||
|
|
||||||
|
|
||||||
|
# Simple lexer for highlighting.
|
||||||
|
# Improve this later.
|
||||||
|
class LambdaLexer(Lexer):
|
||||||
|
def lex_document(self, document):
|
||||||
|
def inner(line_no):
|
||||||
|
return [("class:text", str(document.lines[line_no]))]
|
||||||
|
return inner
|
||||||
|
|
||||||
|
|
||||||
lamb.utils.show_greeting()
|
lamb.utils.show_greeting()
|
||||||
|
|
||||||
|
|
||||||
|
# Replace "\" with pretty "λ"s
|
||||||
|
bindings = KeyBindings()
|
||||||
|
@bindings.add("\\")
|
||||||
|
def _(event):
|
||||||
|
event.current_buffer.insert_text("λ")
|
||||||
|
|
||||||
|
|
||||||
r = lamb.Runner(
|
r = lamb.Runner(
|
||||||
prompt_session = PromptSession(
|
prompt_session = PromptSession(
|
||||||
style = lamb.utils.style,
|
style = lamb.utils.style,
|
||||||
lexer = lamb.utils.LambdaLexer(),
|
lexer = LambdaLexer(),
|
||||||
key_bindings = lamb.utils.bindings
|
key_bindings = bindings
|
||||||
),
|
),
|
||||||
prompt_message = FormattedText([
|
prompt_message = FormattedText([
|
||||||
("class:prompt", "==> ")
|
("class:prompt", "==> ")
|
||||||
])
|
])
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
r.run_lines([
|
||||||
|
"T = λab.a",
|
||||||
|
"F = λab.b",
|
||||||
|
"NOT = λa.(a F T)",
|
||||||
|
"AND = λab.(a b F)",
|
||||||
|
"OR = λab.(a T b)",
|
||||||
|
"XOR = λab.(a (NOT b) b)",
|
||||||
|
"M = λx.(x x)",
|
||||||
|
"W = M M",
|
||||||
|
"Y = λf.( (λx.(f (x x))) (λx.(f (x x))) )",
|
||||||
|
"PAIR = λabi.( i a b )",
|
||||||
|
"S = λnfa.(f (n f a))",
|
||||||
|
"Z = λn.n (λa.F) T",
|
||||||
|
"MULT = λnmf.n (m f)",
|
||||||
|
"H = λp.((PAIR (p F)) (S (p F)))",
|
||||||
|
"D = λn.n H (PAIR 0 0) T",
|
||||||
|
"FAC = λyn.(Z n)(1)(MULT n (y (D n)))"
|
||||||
|
])
|
||||||
|
|
||||||
|
|
||||||
while True:
|
while True:
|
||||||
try:
|
try:
|
||||||
i = r.prompt()
|
i = r.prompt()
|
||||||
@ -52,7 +89,7 @@ while True:
|
|||||||
("class:text", "\n")
|
("class:text", "\n")
|
||||||
]), style = lamb.utils.style)
|
]), style = lamb.utils.style)
|
||||||
continue
|
continue
|
||||||
except lamb.nodes.ReductionError as e:
|
except lamb.node.ReductionError as e:
|
||||||
printf(FormattedText([
|
printf(FormattedText([
|
||||||
("class:err", f"{e.msg}\n")
|
("class:err", f"{e.msg}\n")
|
||||||
]), style = lamb.utils.style)
|
]), style = lamb.utils.style)
|
||||||
|
@ -101,14 +101,7 @@ def cmd_load(command, runner):
|
|||||||
lines = [x.strip() for x in f.readlines()]
|
lines = [x.strip() for x in f.readlines()]
|
||||||
|
|
||||||
for i in range(len(lines)):
|
for i in range(len(lines)):
|
||||||
l = lines[i].strip()
|
l = lines[i]
|
||||||
|
|
||||||
# Skip comments and empty lines
|
|
||||||
if l.startswith("#"):
|
|
||||||
continue
|
|
||||||
if l == "":
|
|
||||||
continue
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
x = runner.parse(l)[0]
|
x = runner.parse(l)[0]
|
||||||
except ppx.ParseException as e:
|
except ppx.ParseException as e:
|
||||||
@ -123,7 +116,7 @@ def cmd_load(command, runner):
|
|||||||
)
|
)
|
||||||
return
|
return
|
||||||
|
|
||||||
if not isinstance(x, lamb.runner.runner.MacroDef):
|
if not isinstance(x, lamb.runner.MacroDef):
|
||||||
printf(
|
printf(
|
||||||
FormattedText([
|
FormattedText([
|
||||||
("class:warn", f"Skipping line {i+1:02}: "),
|
("class:warn", f"Skipping line {i+1:02}: "),
|
||||||
@ -170,40 +163,11 @@ def mdel(command, runner) -> None:
|
|||||||
|
|
||||||
del runner.macro_table[target]
|
del runner.macro_table[target]
|
||||||
|
|
||||||
@lamb_command(
|
|
||||||
help_text = "Delete all macros"
|
|
||||||
)
|
|
||||||
def clearmacros(command, runner) -> None:
|
|
||||||
confirm = runner.prompt_session.prompt(
|
|
||||||
message = FormattedText([
|
|
||||||
("class:warn", "Are you sure? "),
|
|
||||||
("class:text", "[yes/no]: ")
|
|
||||||
])
|
|
||||||
).lower()
|
|
||||||
|
|
||||||
if confirm != "yes":
|
|
||||||
printf(
|
|
||||||
HTML(
|
|
||||||
"<err>Cancelled.</err>"
|
|
||||||
),
|
|
||||||
style = lamb.utils.style
|
|
||||||
)
|
|
||||||
return
|
|
||||||
|
|
||||||
runner.macro_table = {}
|
|
||||||
|
|
||||||
|
|
||||||
@lamb_command(
|
@lamb_command(
|
||||||
help_text = "Show macros"
|
help_text = "Show macros"
|
||||||
)
|
)
|
||||||
def macros(command, runner) -> None:
|
def macros(command, runner) -> None:
|
||||||
if len(runner.macro_table) == 0:
|
|
||||||
printf(FormattedText([
|
|
||||||
("class:warn", "No macros are defined."),
|
|
||||||
]),
|
|
||||||
style = lamb.utils.style
|
|
||||||
)
|
|
||||||
else:
|
|
||||||
printf(FormattedText([
|
printf(FormattedText([
|
||||||
("class:cmd_h", "\nDefined Macros:\n"),
|
("class:cmd_h", "\nDefined Macros:\n"),
|
||||||
] +
|
] +
|
@ -1,5 +1,37 @@
|
|||||||
|
import enum
|
||||||
import lamb
|
import lamb
|
||||||
import lamb.nodes as lbn
|
|
||||||
|
class Direction(enum.Enum):
|
||||||
|
UP = enum.auto()
|
||||||
|
LEFT = enum.auto()
|
||||||
|
RIGHT = enum.auto()
|
||||||
|
|
||||||
|
class ReductionType(enum.Enum):
|
||||||
|
# Nothing happened. This implies that
|
||||||
|
# an expression cannot be reduced further.
|
||||||
|
NOTHING = enum.auto()
|
||||||
|
|
||||||
|
# We replaced a macro with an expression.
|
||||||
|
MACRO_EXPAND = enum.auto()
|
||||||
|
|
||||||
|
# We expanded a history reference
|
||||||
|
HIST_EXPAND = enum.auto()
|
||||||
|
|
||||||
|
# We turned a church numeral into an expression
|
||||||
|
AUTOCHURCH = enum.auto()
|
||||||
|
|
||||||
|
# We applied a function.
|
||||||
|
# This is the only type of "formal" reduction step.
|
||||||
|
FUNCTION_APPLY = enum.auto()
|
||||||
|
|
||||||
|
class ReductionError(Exception):
|
||||||
|
"""
|
||||||
|
Raised when we encounter an error while reducing.
|
||||||
|
|
||||||
|
These should be caught and elegantly presented to the user.
|
||||||
|
"""
|
||||||
|
def __init__(self, msg: str):
|
||||||
|
self.msg = msg
|
||||||
|
|
||||||
class TreeWalker:
|
class TreeWalker:
|
||||||
"""
|
"""
|
||||||
@ -16,7 +48,7 @@ class TreeWalker:
|
|||||||
self.expr = expr
|
self.expr = expr
|
||||||
self.ptr = expr
|
self.ptr = expr
|
||||||
self.first_step = True
|
self.first_step = True
|
||||||
self.from_side = lbn.Direction.UP
|
self.from_side = Direction.UP
|
||||||
|
|
||||||
def __iter__(self):
|
def __iter__(self):
|
||||||
return self
|
return self
|
||||||
@ -32,21 +64,21 @@ class TreeWalker:
|
|||||||
return self.from_side, self.ptr
|
return self.from_side, self.ptr
|
||||||
|
|
||||||
if isinstance(self.ptr, Root):
|
if isinstance(self.ptr, Root):
|
||||||
if self.from_side == lbn.Direction.UP:
|
if self.from_side == Direction.UP:
|
||||||
self.from_side, self.ptr = self.ptr.go_left()
|
self.from_side, self.ptr = self.ptr.go_left()
|
||||||
elif isinstance(self.ptr, EndNode):
|
elif isinstance(self.ptr, EndNode):
|
||||||
self.from_side, self.ptr = self.ptr.go_up()
|
self.from_side, self.ptr = self.ptr.go_up()
|
||||||
elif isinstance(self.ptr, Func):
|
elif isinstance(self.ptr, Func):
|
||||||
if self.from_side == lbn.Direction.UP:
|
if self.from_side == Direction.UP:
|
||||||
self.from_side, self.ptr = self.ptr.go_left()
|
self.from_side, self.ptr = self.ptr.go_left()
|
||||||
elif self.from_side == lbn.Direction.LEFT:
|
elif self.from_side == Direction.LEFT:
|
||||||
self.from_side, self.ptr = self.ptr.go_up()
|
self.from_side, self.ptr = self.ptr.go_up()
|
||||||
elif isinstance(self.ptr, Call):
|
elif isinstance(self.ptr, Call):
|
||||||
if self.from_side == lbn.Direction.UP:
|
if self.from_side == Direction.UP:
|
||||||
self.from_side, self.ptr = self.ptr.go_left()
|
self.from_side, self.ptr = self.ptr.go_left()
|
||||||
elif self.from_side == lbn.Direction.LEFT:
|
elif self.from_side == Direction.LEFT:
|
||||||
self.from_side, self.ptr = self.ptr.go_right()
|
self.from_side, self.ptr = self.ptr.go_right()
|
||||||
elif self.from_side == lbn.Direction.RIGHT:
|
elif self.from_side == Direction.RIGHT:
|
||||||
self.from_side, self.ptr = self.ptr.go_up()
|
self.from_side, self.ptr = self.ptr.go_up()
|
||||||
else:
|
else:
|
||||||
raise TypeError(f"I don't know how to iterate a {type(self.ptr)}")
|
raise TypeError(f"I don't know how to iterate a {type(self.ptr)}")
|
||||||
@ -95,9 +127,9 @@ class Node:
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
if (parent is not None) and (side is None):
|
if (parent is not None) and (side is None):
|
||||||
raise Exception("If a node has a parent, it must have a lbn.direction.")
|
raise Exception("If a node has a parent, it must have a direction.")
|
||||||
if (parent is None) and (side is not None):
|
if (parent is None) and (side is not None):
|
||||||
raise Exception("If a node has no parent, it cannot have a lbn.direction.")
|
raise Exception("If a node has no parent, it cannot have a direction.")
|
||||||
self.parent = parent
|
self.parent = parent
|
||||||
self.parent_side = side
|
self.parent_side = side
|
||||||
return self
|
return self
|
||||||
@ -109,7 +141,7 @@ class Node:
|
|||||||
@left.setter
|
@left.setter
|
||||||
def left(self, node):
|
def left(self, node):
|
||||||
if node is not None:
|
if node is not None:
|
||||||
node._set_parent(self, lbn.Direction.LEFT)
|
node._set_parent(self, Direction.LEFT)
|
||||||
self._left = node
|
self._left = node
|
||||||
|
|
||||||
@property
|
@property
|
||||||
@ -119,27 +151,27 @@ class Node:
|
|||||||
@right.setter
|
@right.setter
|
||||||
def right(self, node):
|
def right(self, node):
|
||||||
if node is not None:
|
if node is not None:
|
||||||
node._set_parent(self, lbn.Direction.RIGHT)
|
node._set_parent(self, Direction.RIGHT)
|
||||||
self._right = node
|
self._right = node
|
||||||
|
|
||||||
|
|
||||||
def set_side(self, side: lbn.Direction, node):
|
def set_side(self, side: Direction, node):
|
||||||
"""
|
"""
|
||||||
A wrapper around Node.left and Node.right that
|
A wrapper around Node.left and Node.right that
|
||||||
automatically selects a side.
|
automatically selects a side.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
if side == lbn.Direction.LEFT:
|
if side == Direction.LEFT:
|
||||||
self.left = node
|
self.left = node
|
||||||
elif side == lbn.Direction.RIGHT:
|
elif side == Direction.RIGHT:
|
||||||
self.right = node
|
self.right = node
|
||||||
else:
|
else:
|
||||||
raise TypeError("Can only set left or right side.")
|
raise TypeError("Can only set left or right side.")
|
||||||
|
|
||||||
def get_side(self, side: lbn.Direction):
|
def get_side(self, side: Direction):
|
||||||
if side == lbn.Direction.LEFT:
|
if side == Direction.LEFT:
|
||||||
return self.left
|
return self.left
|
||||||
elif side == lbn.Direction.RIGHT:
|
elif side == Direction.RIGHT:
|
||||||
return self.right
|
return self.right
|
||||||
else:
|
else:
|
||||||
raise TypeError("Can only get left or right side.")
|
raise TypeError("Can only get left or right side.")
|
||||||
@ -156,7 +188,7 @@ class Node:
|
|||||||
|
|
||||||
if self._left is None:
|
if self._left is None:
|
||||||
raise Exception("Can't go left when left is None")
|
raise Exception("Can't go left when left is None")
|
||||||
return lbn.Direction.UP, self._left
|
return Direction.UP, self._left
|
||||||
|
|
||||||
def go_right(self):
|
def go_right(self):
|
||||||
"""
|
"""
|
||||||
@ -168,7 +200,7 @@ class Node:
|
|||||||
"""
|
"""
|
||||||
if self._right is None:
|
if self._right is None:
|
||||||
raise Exception("Can't go right when right is None")
|
raise Exception("Can't go right when right is None")
|
||||||
return lbn.Direction.UP, self._right
|
return Direction.UP, self._right
|
||||||
|
|
||||||
def go_up(self):
|
def go_up(self):
|
||||||
"""
|
"""
|
||||||
@ -189,17 +221,17 @@ class Node:
|
|||||||
raise NotImplementedError("Nodes MUST provide a `copy` method!")
|
raise NotImplementedError("Nodes MUST provide a `copy` method!")
|
||||||
|
|
||||||
def __str__(self) -> str:
|
def __str__(self) -> str:
|
||||||
return lbn.print_node(self)
|
return print_node(self)
|
||||||
|
|
||||||
def export(self) -> str:
|
def export(self) -> str:
|
||||||
"""
|
"""
|
||||||
Convert this tree to a parsable string.
|
Convert this tree to a parsable string.
|
||||||
"""
|
"""
|
||||||
return lbn.print_node(self, export = True)
|
return print_node(self, export = True)
|
||||||
|
|
||||||
def set_runner(self, runner):
|
def set_runner(self, runner):
|
||||||
for s, n in self:
|
for s, n in self:
|
||||||
if s == lbn.Direction.UP:
|
if s == Direction.UP:
|
||||||
n.runner = runner # type: ignore
|
n.runner = runner # type: ignore
|
||||||
return self
|
return self
|
||||||
|
|
||||||
@ -209,7 +241,7 @@ class EndNode(Node):
|
|||||||
|
|
||||||
class ExpandableEndNode(EndNode):
|
class ExpandableEndNode(EndNode):
|
||||||
always_expand = False
|
always_expand = False
|
||||||
def expand(self) -> tuple[lbn.ReductionType, Node]:
|
def expand(self) -> tuple[ReductionType, Node]:
|
||||||
raise NotImplementedError("ExpandableEndNodes MUST provide an `expand` method!")
|
raise NotImplementedError("ExpandableEndNodes MUST provide an `expand` method!")
|
||||||
|
|
||||||
class FreeVar(EndNode):
|
class FreeVar(EndNode):
|
||||||
@ -248,13 +280,13 @@ class Macro(ExpandableEndNode):
|
|||||||
def print_value(self, *, export: bool = False) -> str:
|
def print_value(self, *, export: bool = False) -> str:
|
||||||
return self.name
|
return self.name
|
||||||
|
|
||||||
def expand(self) -> tuple[lbn.ReductionType, Node]:
|
def expand(self) -> tuple[ReductionType, Node]:
|
||||||
if self.name in self.runner.macro_table:
|
if self.name in self.runner.macro_table:
|
||||||
# The element in the macro table will be a Root node,
|
# The element in the macro table will be a Root node,
|
||||||
# so we clone its left element.
|
# so we clone its left element.
|
||||||
return (
|
return (
|
||||||
lbn.ReductionType.MACRO_EXPAND,
|
ReductionType.MACRO_EXPAND,
|
||||||
lbn.clone(self.runner.macro_table[self.name].left)
|
clone(self.runner.macro_table[self.name].left)
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
raise Exception(f"Macro {self.name} is not defined")
|
raise Exception(f"Macro {self.name} is not defined")
|
||||||
@ -283,16 +315,16 @@ class Church(ExpandableEndNode):
|
|||||||
def print_value(self, *, export: bool = False) -> str:
|
def print_value(self, *, export: bool = False) -> str:
|
||||||
return str(self.value)
|
return str(self.value)
|
||||||
|
|
||||||
def expand(self) -> tuple[lbn.ReductionType, Node]:
|
def expand(self) -> tuple[ReductionType, Node]:
|
||||||
f = Bound("f")
|
f = Bound("f")
|
||||||
a = Bound("a")
|
a = Bound("a")
|
||||||
chain = a
|
chain = a
|
||||||
|
|
||||||
for i in range(self.value):
|
for i in range(self.value):
|
||||||
chain = Call(lbn.clone(f), lbn.clone(chain))
|
chain = Call(clone(f), clone(chain))
|
||||||
|
|
||||||
return (
|
return (
|
||||||
lbn.ReductionType.AUTOCHURCH,
|
ReductionType.AUTOCHURCH,
|
||||||
Func(f, Func(a, chain)).set_runner(self.runner)
|
Func(f, Func(a, chain)).set_runner(self.runner)
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -318,13 +350,13 @@ class History(ExpandableEndNode):
|
|||||||
def print_value(self, *, export: bool = False) -> str:
|
def print_value(self, *, export: bool = False) -> str:
|
||||||
return "$"
|
return "$"
|
||||||
|
|
||||||
def expand(self) -> tuple[lbn.ReductionType, Node]:
|
def expand(self) -> tuple[ReductionType, Node]:
|
||||||
if len(self.runner.history) == 0:
|
if len(self.runner.history) == 0:
|
||||||
raise lbn.ReductionError(f"There isn't any history to reference.")
|
raise ReductionError(f"There isn't any history to reference.")
|
||||||
# .left is VERY important!
|
# .left is VERY important!
|
||||||
# self.runner.history will contain Root nodes,
|
# self.runner.history will contain Root nodes,
|
||||||
# and we don't want those *inside* our tree.
|
# and we don't want those *inside* our tree.
|
||||||
return lbn.ReductionType.HIST_EXPAND, lbn.clone(self.runner.history[-1].left)
|
return ReductionType.HIST_EXPAND, clone(self.runner.history[-1].left)
|
||||||
|
|
||||||
def copy(self):
|
def copy(self):
|
||||||
return History(runner = self.runner)
|
return History(runner = self.runner)
|
||||||
@ -432,3 +464,225 @@ class Call(Node):
|
|||||||
|
|
||||||
def copy(self):
|
def copy(self):
|
||||||
return Call(None, None, runner = self.runner) # type: ignore
|
return Call(None, None, runner = self.runner) # type: ignore
|
||||||
|
|
||||||
|
|
||||||
|
def print_node(node: Node, *, export: bool = False) -> str:
|
||||||
|
if not isinstance(node, Node):
|
||||||
|
raise TypeError(f"I don't know how to print a {type(node)}")
|
||||||
|
|
||||||
|
out = ""
|
||||||
|
|
||||||
|
bound_subs = {}
|
||||||
|
|
||||||
|
for s, n in node:
|
||||||
|
if isinstance(n, EndNode):
|
||||||
|
if isinstance(n, Bound):
|
||||||
|
if n.identifier not in bound_subs.keys():
|
||||||
|
o = n.print_value(export = export)
|
||||||
|
if o in bound_subs.items():
|
||||||
|
i = 1
|
||||||
|
while o in bound_subs.items():
|
||||||
|
o = lamb.utils.subscript(i := i + 1)
|
||||||
|
bound_subs[n.identifier] = o
|
||||||
|
else:
|
||||||
|
bound_subs[n.identifier] = n.print_value()
|
||||||
|
|
||||||
|
|
||||||
|
out += bound_subs[n.identifier]
|
||||||
|
else:
|
||||||
|
out += n.print_value(export = export)
|
||||||
|
|
||||||
|
elif isinstance(n, Func):
|
||||||
|
if s == Direction.UP:
|
||||||
|
if isinstance(n.parent, Func):
|
||||||
|
out += n.input.name
|
||||||
|
else:
|
||||||
|
out += "λ" + n.input.name
|
||||||
|
if not isinstance(n.left, Func):
|
||||||
|
out += "."
|
||||||
|
|
||||||
|
elif isinstance(n, Call):
|
||||||
|
if s == Direction.UP:
|
||||||
|
out += "("
|
||||||
|
elif s == Direction.LEFT:
|
||||||
|
out += " "
|
||||||
|
elif s == Direction.RIGHT:
|
||||||
|
out += ")"
|
||||||
|
|
||||||
|
return out
|
||||||
|
|
||||||
|
def clone(node: Node):
|
||||||
|
if not isinstance(node, Node):
|
||||||
|
raise TypeError(f"I don't know what to do with a {type(node)}")
|
||||||
|
|
||||||
|
out = node.copy()
|
||||||
|
out_ptr = out # Stays one step behind ptr, in the new tree.
|
||||||
|
ptr = node
|
||||||
|
from_side = Direction.UP
|
||||||
|
|
||||||
|
if isinstance(node, EndNode):
|
||||||
|
return out
|
||||||
|
|
||||||
|
# We're not using a TreeWalker here because
|
||||||
|
# we need more control over our pointer when cloning.
|
||||||
|
while True:
|
||||||
|
if isinstance(ptr, EndNode):
|
||||||
|
from_side, ptr = ptr.go_up()
|
||||||
|
_, out_ptr = out_ptr.go_up()
|
||||||
|
elif isinstance(ptr, Func) or isinstance(ptr, Root):
|
||||||
|
if from_side == Direction.UP:
|
||||||
|
from_side, ptr = ptr.go_left()
|
||||||
|
out_ptr.set_side(ptr.parent_side, ptr.copy())
|
||||||
|
_, out_ptr = out_ptr.go_left()
|
||||||
|
elif from_side == Direction.LEFT:
|
||||||
|
from_side, ptr = ptr.go_up()
|
||||||
|
_, out_ptr = out_ptr.go_up()
|
||||||
|
elif isinstance(ptr, Call):
|
||||||
|
if from_side == Direction.UP:
|
||||||
|
from_side, ptr = ptr.go_left()
|
||||||
|
out_ptr.set_side(ptr.parent_side, ptr.copy())
|
||||||
|
_, out_ptr = out_ptr.go_left()
|
||||||
|
elif from_side == Direction.LEFT:
|
||||||
|
from_side, ptr = ptr.go_right()
|
||||||
|
out_ptr.set_side(ptr.parent_side, ptr.copy())
|
||||||
|
_, out_ptr = out_ptr.go_right()
|
||||||
|
elif from_side == Direction.RIGHT:
|
||||||
|
from_side, ptr = ptr.go_up()
|
||||||
|
_, out_ptr = out_ptr.go_up()
|
||||||
|
|
||||||
|
if ptr is node.parent:
|
||||||
|
break
|
||||||
|
return out
|
||||||
|
|
||||||
|
def prepare(root: Root, *, ban_macro_name = None) -> dict:
|
||||||
|
"""
|
||||||
|
Prepare an expression for expansion.
|
||||||
|
This will does the following:
|
||||||
|
- Binds variables
|
||||||
|
- Turns unbound macros into free variables
|
||||||
|
- Generates warnings
|
||||||
|
"""
|
||||||
|
|
||||||
|
if not isinstance(root, Root):
|
||||||
|
raise TypeError(f"I don't know what to do with a {type(root)}")
|
||||||
|
|
||||||
|
bound_variables = {}
|
||||||
|
|
||||||
|
output = {
|
||||||
|
"has_history": False,
|
||||||
|
"free_variables": set()
|
||||||
|
}
|
||||||
|
|
||||||
|
it = iter(root)
|
||||||
|
for s, n in it:
|
||||||
|
if isinstance(n, History):
|
||||||
|
output["has_history"] = True
|
||||||
|
|
||||||
|
# If this expression is part of a macro,
|
||||||
|
# make sure we don't reference it inside itself.
|
||||||
|
elif isinstance(n, Macro):
|
||||||
|
if (n.name == ban_macro_name) and (ban_macro_name is not None):
|
||||||
|
raise ReductionError("Macro cannot reference self")
|
||||||
|
|
||||||
|
# Bind variables
|
||||||
|
if n.name in bound_variables:
|
||||||
|
n.parent.set_side(
|
||||||
|
n.parent_side,
|
||||||
|
clone(bound_variables[n.name])
|
||||||
|
)
|
||||||
|
it.ptr = n.parent.get_side(n.parent_side)
|
||||||
|
|
||||||
|
# Turn undefined macros into free variables
|
||||||
|
elif n.name not in root.runner.macro_table:
|
||||||
|
output["free_variables"].add(n.name)
|
||||||
|
n.parent.set_side(
|
||||||
|
n.parent_side,
|
||||||
|
n.to_freevar()
|
||||||
|
)
|
||||||
|
it.ptr = n.parent.get_side(n.parent_side)
|
||||||
|
|
||||||
|
|
||||||
|
# Save bound variables when we enter a function's sub-tree,
|
||||||
|
# delete them when we exit it.
|
||||||
|
elif isinstance(n, Func):
|
||||||
|
if s == Direction.UP:
|
||||||
|
# Add this function's input to the table of bound variables.
|
||||||
|
# If it is already there, raise an error.
|
||||||
|
if (n.input.name in bound_variables):
|
||||||
|
raise ReductionError(f"Bound variable name conflict: \"{n.input.name}\"")
|
||||||
|
else:
|
||||||
|
bound_variables[n.input.name] = Bound(n.input.name)
|
||||||
|
n.input = bound_variables[n.input.name]
|
||||||
|
|
||||||
|
elif s == Direction.LEFT:
|
||||||
|
del bound_variables[n.input.name]
|
||||||
|
|
||||||
|
return output
|
||||||
|
|
||||||
|
# Apply a function.
|
||||||
|
# Returns the function's output.
|
||||||
|
def call_func(fn: Func, arg: Node):
|
||||||
|
for s, n in fn:
|
||||||
|
if isinstance(n, Bound) and (s == Direction.UP):
|
||||||
|
if n == fn.input:
|
||||||
|
if n.parent is None:
|
||||||
|
raise Exception("Tried to substitute a None bound variable.")
|
||||||
|
|
||||||
|
n.parent.set_side(n.parent_side, clone(arg)) # type: ignore
|
||||||
|
return fn.left
|
||||||
|
|
||||||
|
# Do a single reduction step
|
||||||
|
def reduce(root: Root) -> tuple[ReductionType, Root]:
|
||||||
|
if not isinstance(root, Root):
|
||||||
|
raise TypeError(f"I can't reduce a {type(root)}")
|
||||||
|
|
||||||
|
out = root
|
||||||
|
for s, n in out:
|
||||||
|
if isinstance(n, Call) and (s == Direction.UP):
|
||||||
|
if isinstance(n.left, Func):
|
||||||
|
n.parent.set_side(
|
||||||
|
n.parent_side, # type: ignore
|
||||||
|
call_func(n.left, n.right)
|
||||||
|
)
|
||||||
|
|
||||||
|
return ReductionType.FUNCTION_APPLY, out
|
||||||
|
|
||||||
|
elif isinstance(n.left, ExpandableEndNode):
|
||||||
|
r, n.left = n.left.expand()
|
||||||
|
return r, out
|
||||||
|
return ReductionType.NOTHING, out
|
||||||
|
|
||||||
|
|
||||||
|
def expand(root: Root, *, force_all = False) -> tuple[int, Root]:
|
||||||
|
"""
|
||||||
|
Expands expandable nodes in the given tree.
|
||||||
|
|
||||||
|
If force_all is false, this only expands
|
||||||
|
ExpandableEndnodes that have "always_expand" set to True.
|
||||||
|
|
||||||
|
If force_all is True, this expands ALL
|
||||||
|
ExpandableEndnodes.
|
||||||
|
"""
|
||||||
|
|
||||||
|
if not isinstance(root, Root):
|
||||||
|
raise TypeError(f"I don't know what to do with a {type(root)}")
|
||||||
|
|
||||||
|
out = root
|
||||||
|
macro_expansions = 0
|
||||||
|
|
||||||
|
it = iter(root)
|
||||||
|
for s, n in it:
|
||||||
|
if (
|
||||||
|
isinstance(n, ExpandableEndNode) and
|
||||||
|
(force_all or n.always_expand)
|
||||||
|
):
|
||||||
|
|
||||||
|
n.parent.set_side(
|
||||||
|
n.parent_side, # type: ignore
|
||||||
|
n.expand()[1]
|
||||||
|
)
|
||||||
|
it.ptr = n.parent.get_side(
|
||||||
|
n.parent_side # type: ignore
|
||||||
|
)
|
||||||
|
macro_expansions += 1
|
||||||
|
return macro_expansions, out
|
@ -1,3 +0,0 @@
|
|||||||
from .misc import *
|
|
||||||
from .nodes import *
|
|
||||||
from .functions import *
|
|
@ -1,229 +0,0 @@
|
|||||||
import lamb
|
|
||||||
import lamb.nodes as lbn
|
|
||||||
|
|
||||||
def print_node(node: lbn.Node, *, export: bool = False) -> str:
|
|
||||||
if not isinstance(node, lbn.Node):
|
|
||||||
raise TypeError(f"I don't know how to print a {type(node)}")
|
|
||||||
|
|
||||||
out = ""
|
|
||||||
|
|
||||||
bound_subs = {}
|
|
||||||
|
|
||||||
for s, n in node:
|
|
||||||
if isinstance(n, lbn.EndNode):
|
|
||||||
if isinstance(n, lbn.Bound):
|
|
||||||
if n.identifier not in bound_subs.keys():
|
|
||||||
o = n.print_value(export = export)
|
|
||||||
if o in bound_subs.items():
|
|
||||||
i = 1
|
|
||||||
while o in bound_subs.items():
|
|
||||||
o = lamb.utils.subscript(i := i + 1)
|
|
||||||
bound_subs[n.identifier] = o
|
|
||||||
else:
|
|
||||||
bound_subs[n.identifier] = n.print_value()
|
|
||||||
|
|
||||||
|
|
||||||
out += bound_subs[n.identifier]
|
|
||||||
else:
|
|
||||||
out += n.print_value(export = export)
|
|
||||||
|
|
||||||
elif isinstance(n, lbn.Func):
|
|
||||||
if s == lbn.Direction.UP:
|
|
||||||
if isinstance(n.parent, lbn.Call):
|
|
||||||
out += "("
|
|
||||||
|
|
||||||
if isinstance(n.parent, lbn.Func):
|
|
||||||
out += n.input.name
|
|
||||||
else:
|
|
||||||
out += "λ" + n.input.name
|
|
||||||
if not isinstance(n.left, lbn.Func):
|
|
||||||
out += "."
|
|
||||||
elif s == lbn.Direction.LEFT:
|
|
||||||
if isinstance(n.parent, lbn.Call):
|
|
||||||
out += ")"
|
|
||||||
|
|
||||||
elif isinstance(n, lbn.Call):
|
|
||||||
if s == lbn.Direction.UP:
|
|
||||||
out += "("
|
|
||||||
elif s == lbn.Direction.LEFT:
|
|
||||||
out += " "
|
|
||||||
elif s == lbn.Direction.RIGHT:
|
|
||||||
out += ")"
|
|
||||||
|
|
||||||
return out
|
|
||||||
|
|
||||||
def clone(node: lbn.Node):
|
|
||||||
if not isinstance(node, lbn.Node):
|
|
||||||
raise TypeError(f"I don't know what to do with a {type(node)}")
|
|
||||||
|
|
||||||
out = node.copy()
|
|
||||||
out_ptr = out # Stays one step behind ptr, in the new tree.
|
|
||||||
ptr = node
|
|
||||||
from_side = lbn.Direction.UP
|
|
||||||
|
|
||||||
if isinstance(node, lbn.EndNode):
|
|
||||||
return out
|
|
||||||
|
|
||||||
# We're not using a TreeWalker here because
|
|
||||||
# we need more control over our pointer when cloning.
|
|
||||||
while True:
|
|
||||||
if isinstance(ptr, lbn.EndNode):
|
|
||||||
from_side, ptr = ptr.go_up()
|
|
||||||
_, out_ptr = out_ptr.go_up()
|
|
||||||
elif isinstance(ptr, lbn.Func) or isinstance(ptr, lbn.Root):
|
|
||||||
if from_side == lbn.Direction.UP:
|
|
||||||
from_side, ptr = ptr.go_left()
|
|
||||||
out_ptr.set_side(ptr.parent_side, ptr.copy())
|
|
||||||
_, out_ptr = out_ptr.go_left()
|
|
||||||
elif from_side == lbn.Direction.LEFT:
|
|
||||||
from_side, ptr = ptr.go_up()
|
|
||||||
_, out_ptr = out_ptr.go_up()
|
|
||||||
elif isinstance(ptr, lbn.Call):
|
|
||||||
if from_side == lbn.Direction.UP:
|
|
||||||
from_side, ptr = ptr.go_left()
|
|
||||||
out_ptr.set_side(ptr.parent_side, ptr.copy())
|
|
||||||
_, out_ptr = out_ptr.go_left()
|
|
||||||
elif from_side == lbn.Direction.LEFT:
|
|
||||||
from_side, ptr = ptr.go_right()
|
|
||||||
out_ptr.set_side(ptr.parent_side, ptr.copy())
|
|
||||||
_, out_ptr = out_ptr.go_right()
|
|
||||||
elif from_side == lbn.Direction.RIGHT:
|
|
||||||
from_side, ptr = ptr.go_up()
|
|
||||||
_, out_ptr = out_ptr.go_up()
|
|
||||||
|
|
||||||
if ptr is node.parent:
|
|
||||||
break
|
|
||||||
return out
|
|
||||||
|
|
||||||
def prepare(root: lbn.Root, *, ban_macro_name = None) -> dict:
|
|
||||||
"""
|
|
||||||
Prepare an expression for expansion.
|
|
||||||
This will does the following:
|
|
||||||
- Binds variables
|
|
||||||
- Turns unbound macros into free variables
|
|
||||||
- Generates warnings
|
|
||||||
"""
|
|
||||||
|
|
||||||
if not isinstance(root, lbn.Root):
|
|
||||||
raise TypeError(f"I don't know what to do with a {type(root)}")
|
|
||||||
|
|
||||||
bound_variables = {}
|
|
||||||
|
|
||||||
output = {
|
|
||||||
"has_history": False,
|
|
||||||
"free_variables": set()
|
|
||||||
}
|
|
||||||
|
|
||||||
it = iter(root)
|
|
||||||
for s, n in it:
|
|
||||||
if isinstance(n, lbn.History):
|
|
||||||
output["has_history"] = True
|
|
||||||
|
|
||||||
# If this expression is part of a macro,
|
|
||||||
# make sure we don't reference it inside itself.
|
|
||||||
elif isinstance(n, lbn.Macro):
|
|
||||||
if (n.name == ban_macro_name) and (ban_macro_name is not None):
|
|
||||||
raise lbn.ReductionError("Macro cannot reference self")
|
|
||||||
|
|
||||||
# Bind variables
|
|
||||||
if n.name in bound_variables:
|
|
||||||
n.parent.set_side(
|
|
||||||
n.parent_side,
|
|
||||||
clone(bound_variables[n.name])
|
|
||||||
)
|
|
||||||
it.ptr = n.parent.get_side(n.parent_side)
|
|
||||||
|
|
||||||
# Turn undefined macros into free variables
|
|
||||||
elif n.name not in root.runner.macro_table:
|
|
||||||
output["free_variables"].add(n.name)
|
|
||||||
n.parent.set_side(
|
|
||||||
n.parent_side,
|
|
||||||
n.to_freevar()
|
|
||||||
)
|
|
||||||
it.ptr = n.parent.get_side(n.parent_side)
|
|
||||||
|
|
||||||
|
|
||||||
# Save bound variables when we enter a function's sub-tree,
|
|
||||||
# delete them when we exit it.
|
|
||||||
elif isinstance(n, lbn.Func):
|
|
||||||
if s == lbn.Direction.UP:
|
|
||||||
# Add this function's input to the table of bound variables.
|
|
||||||
# If it is already there, raise an error.
|
|
||||||
if (n.input.name in bound_variables):
|
|
||||||
raise lbn.ReductionError(f"Bound variable name conflict: \"{n.input.name}\"")
|
|
||||||
else:
|
|
||||||
bound_variables[n.input.name] = lbn.Bound(n.input.name)
|
|
||||||
n.input = bound_variables[n.input.name]
|
|
||||||
|
|
||||||
elif s == lbn.Direction.LEFT:
|
|
||||||
del bound_variables[n.input.name]
|
|
||||||
|
|
||||||
return output
|
|
||||||
|
|
||||||
# Apply a function.
|
|
||||||
# Returns the function's output.
|
|
||||||
def call_func(fn: lbn.Func, arg: lbn.Node):
|
|
||||||
for s, n in fn:
|
|
||||||
if isinstance(n, lbn.Bound) and (s == lbn.Direction.UP):
|
|
||||||
if n == fn.input:
|
|
||||||
if n.parent is None:
|
|
||||||
raise Exception("Tried to substitute a None bound variable.")
|
|
||||||
|
|
||||||
n.parent.set_side(n.parent_side, clone(arg)) # type: ignore
|
|
||||||
return fn.left
|
|
||||||
|
|
||||||
# Do a single reduction step
|
|
||||||
def reduce(root: lbn.Root) -> tuple[lbn.ReductionType, lbn.Root]:
|
|
||||||
if not isinstance(root, lbn.Root):
|
|
||||||
raise TypeError(f"I can't reduce a {type(root)}")
|
|
||||||
|
|
||||||
out = root
|
|
||||||
for s, n in out:
|
|
||||||
if isinstance(n, lbn.Call) and (s == lbn.Direction.UP):
|
|
||||||
if isinstance(n.left, lbn.Func):
|
|
||||||
n.parent.set_side(
|
|
||||||
n.parent_side, # type: ignore
|
|
||||||
call_func(n.left, n.right)
|
|
||||||
)
|
|
||||||
|
|
||||||
return lbn.ReductionType.FUNCTION_APPLY, out
|
|
||||||
|
|
||||||
elif isinstance(n.left, lbn.ExpandableEndNode):
|
|
||||||
r, n.left = n.left.expand()
|
|
||||||
return r, out
|
|
||||||
return lbn.ReductionType.NOTHING, out
|
|
||||||
|
|
||||||
|
|
||||||
def expand(root: lbn.Root, *, force_all = False) -> tuple[int, lbn.Root]:
|
|
||||||
"""
|
|
||||||
Expands expandable nodes in the given tree.
|
|
||||||
|
|
||||||
If force_all is false, this only expands
|
|
||||||
ExpandableEndnodes that have "always_expand" set to True.
|
|
||||||
|
|
||||||
If force_all is True, this expands ALL
|
|
||||||
ExpandableEndnodes.
|
|
||||||
"""
|
|
||||||
|
|
||||||
if not isinstance(root, lbn.Root):
|
|
||||||
raise TypeError(f"I don't know what to do with a {type(root)}")
|
|
||||||
|
|
||||||
out = root
|
|
||||||
macro_expansions = 0
|
|
||||||
|
|
||||||
it = iter(root)
|
|
||||||
for s, n in it:
|
|
||||||
if (
|
|
||||||
isinstance(n, lbn.ExpandableEndNode) and
|
|
||||||
(force_all or n.always_expand)
|
|
||||||
):
|
|
||||||
|
|
||||||
n.parent.set_side(
|
|
||||||
n.parent_side, # type: ignore
|
|
||||||
n.expand()[1]
|
|
||||||
)
|
|
||||||
it.ptr = n.parent.get_side(
|
|
||||||
n.parent_side # type: ignore
|
|
||||||
)
|
|
||||||
macro_expansions += 1
|
|
||||||
return macro_expansions, out
|
|
@ -1,33 +0,0 @@
|
|||||||
import enum
|
|
||||||
|
|
||||||
class Direction(enum.Enum):
|
|
||||||
UP = enum.auto()
|
|
||||||
LEFT = enum.auto()
|
|
||||||
RIGHT = enum.auto()
|
|
||||||
|
|
||||||
class ReductionType(enum.Enum):
|
|
||||||
# Nothing happened. This implies that
|
|
||||||
# an expression cannot be reduced further.
|
|
||||||
NOTHING = enum.auto()
|
|
||||||
|
|
||||||
# We replaced a macro with an expression.
|
|
||||||
MACRO_EXPAND = enum.auto()
|
|
||||||
|
|
||||||
# We expanded a history reference
|
|
||||||
HIST_EXPAND = enum.auto()
|
|
||||||
|
|
||||||
# We turned a church numeral into an expression
|
|
||||||
AUTOCHURCH = enum.auto()
|
|
||||||
|
|
||||||
# We applied a function.
|
|
||||||
# This is the only type of "formal" reduction step.
|
|
||||||
FUNCTION_APPLY = enum.auto()
|
|
||||||
|
|
||||||
class ReductionError(Exception):
|
|
||||||
"""
|
|
||||||
Raised when we encounter an error while reducing.
|
|
||||||
|
|
||||||
These should be caught and elegantly presented to the user.
|
|
||||||
"""
|
|
||||||
def __init__(self, msg: str):
|
|
||||||
self.msg = msg
|
|
@ -56,7 +56,7 @@ class LambdaParser:
|
|||||||
(self.lp + self.pp_history + self.rp)
|
(self.lp + self.pp_history + self.rp)
|
||||||
)
|
)
|
||||||
|
|
||||||
self.pp_command = pp.Suppress(":") + pp.Word(pp.alphas + "_") + pp.Word(pp.alphas + pp.nums + "_.")[0, ...]
|
self.pp_command = pp.Suppress(":") + pp.Word(pp.alphas + "_") + pp.Word(pp.alphas + pp.nums + "_")[0, ...]
|
||||||
|
|
||||||
|
|
||||||
self.pp_all = (
|
self.pp_all = (
|
||||||
|
@ -7,11 +7,46 @@ import time
|
|||||||
|
|
||||||
import lamb
|
import lamb
|
||||||
|
|
||||||
from lamb.runner.misc import MacroDef
|
|
||||||
from lamb.runner.misc import Command
|
|
||||||
from lamb.runner.misc import StopReason
|
|
||||||
from lamb.runner import commands as cmd
|
|
||||||
|
|
||||||
|
class StopReason(enum.Enum):
|
||||||
|
BETA_NORMAL = ("class:text", "β-normal form")
|
||||||
|
LOOP_DETECTED = ("class:warn", "Loop detected")
|
||||||
|
MAX_EXCEEDED = ("class:err", "Too many reductions")
|
||||||
|
INTERRUPT = ("class:warn", "User interrupt")
|
||||||
|
SHOW_MACRO = ("class:text", "Displaying macro content")
|
||||||
|
|
||||||
|
class MacroDef:
|
||||||
|
@staticmethod
|
||||||
|
def from_parse(result):
|
||||||
|
return MacroDef(
|
||||||
|
result[0].name,
|
||||||
|
result[1]
|
||||||
|
)
|
||||||
|
|
||||||
|
def __init__(self, label: str, expr: lamb.node.Node):
|
||||||
|
self.label = label
|
||||||
|
self.expr = expr
|
||||||
|
|
||||||
|
def __repr__(self):
|
||||||
|
return f"<{self.label} := {self.expr!r}>"
|
||||||
|
|
||||||
|
def __str__(self):
|
||||||
|
return f"{self.label} := {self.expr}"
|
||||||
|
|
||||||
|
def set_runner(self, runner):
|
||||||
|
return self.expr.set_runner(runner)
|
||||||
|
|
||||||
|
class Command:
|
||||||
|
@staticmethod
|
||||||
|
def from_parse(result):
|
||||||
|
return Command(
|
||||||
|
result[0],
|
||||||
|
result[1:]
|
||||||
|
)
|
||||||
|
|
||||||
|
def __init__(self, name, args):
|
||||||
|
self.name = name
|
||||||
|
self.args = args
|
||||||
|
|
||||||
|
|
||||||
class Runner:
|
class Runner:
|
||||||
@ -24,14 +59,14 @@ class Runner:
|
|||||||
self.prompt_session = prompt_session
|
self.prompt_session = prompt_session
|
||||||
self.prompt_message = prompt_message
|
self.prompt_message = prompt_message
|
||||||
self.parser = lamb.parser.LambdaParser(
|
self.parser = lamb.parser.LambdaParser(
|
||||||
action_func = lamb.nodes.Func.from_parse,
|
action_func = lamb.node.Func.from_parse,
|
||||||
action_bound = lamb.nodes.Macro.from_parse,
|
action_bound = lamb.node.Macro.from_parse,
|
||||||
action_macro = lamb.nodes.Macro.from_parse,
|
action_macro = lamb.node.Macro.from_parse,
|
||||||
action_call = lamb.nodes.Call.from_parse,
|
action_call = lamb.node.Call.from_parse,
|
||||||
action_church = lamb.nodes.Church.from_parse,
|
action_church = lamb.node.Church.from_parse,
|
||||||
action_macro_def = MacroDef.from_parse,
|
action_macro_def = MacroDef.from_parse,
|
||||||
action_command = Command.from_parse,
|
action_command = Command.from_parse,
|
||||||
action_history = lamb.nodes.History.from_parse
|
action_history = lamb.node.History.from_parse
|
||||||
)
|
)
|
||||||
|
|
||||||
# Maximum amount of reductions.
|
# Maximum amount of reductions.
|
||||||
@ -49,30 +84,30 @@ class Runner:
|
|||||||
# so that all digits appear to be changing.
|
# so that all digits appear to be changing.
|
||||||
self.iter_update = 231
|
self.iter_update = 231
|
||||||
|
|
||||||
self.history: list[lamb.nodes.Root] = []
|
self.history: list[lamb.node.Root] = []
|
||||||
|
|
||||||
def prompt(self):
|
def prompt(self):
|
||||||
return self.prompt_session.prompt(
|
return self.prompt_session.prompt(
|
||||||
message = self.prompt_message
|
message = self.prompt_message
|
||||||
)
|
)
|
||||||
|
|
||||||
def parse(self, line) -> tuple[lamb.nodes.Root | MacroDef | Command, dict]:
|
def parse(self, line) -> tuple[lamb.node.Root | MacroDef | Command, dict]:
|
||||||
e = self.parser.parse_line(line)
|
e = self.parser.parse_line(line)
|
||||||
|
|
||||||
o = {}
|
o = {}
|
||||||
if isinstance(e, MacroDef):
|
if isinstance(e, MacroDef):
|
||||||
e.expr = lamb.nodes.Root(e.expr)
|
e.expr = lamb.node.Root(e.expr)
|
||||||
e.set_runner(self)
|
e.set_runner(self)
|
||||||
o = lamb.nodes.prepare(e.expr, ban_macro_name = e.label)
|
o = lamb.node.prepare(e.expr, ban_macro_name = e.label)
|
||||||
elif isinstance(e, lamb.nodes.Node):
|
elif isinstance(e, lamb.node.Node):
|
||||||
e = lamb.nodes.Root(e)
|
e = lamb.node.Root(e)
|
||||||
e.set_runner(self)
|
e.set_runner(self)
|
||||||
o = lamb.nodes.prepare(e)
|
o = lamb.node.prepare(e)
|
||||||
|
|
||||||
return e, o
|
return e, o
|
||||||
|
|
||||||
|
|
||||||
def reduce(self, node: lamb.nodes.Root, *, status = {}) -> None:
|
def reduce(self, node: lamb.node.Root, *, status = {}) -> None:
|
||||||
|
|
||||||
warning_text = []
|
warning_text = []
|
||||||
|
|
||||||
@ -95,12 +130,12 @@ class Runner:
|
|||||||
]
|
]
|
||||||
|
|
||||||
only_macro = (
|
only_macro = (
|
||||||
isinstance(node.left, lamb.nodes.Macro) or
|
isinstance(node.left, lamb.node.Macro) or
|
||||||
isinstance(node.left, lamb.nodes.Church)
|
isinstance(node.left, lamb.node.Church)
|
||||||
)
|
)
|
||||||
if only_macro:
|
if only_macro:
|
||||||
stop_reason = StopReason.SHOW_MACRO
|
stop_reason = StopReason.SHOW_MACRO
|
||||||
m, node = lamb.nodes.expand(node, force_all = only_macro)
|
m, node = lamb.node.expand(node, force_all = only_macro)
|
||||||
macro_expansions += m
|
macro_expansions += m
|
||||||
|
|
||||||
|
|
||||||
@ -127,20 +162,20 @@ class Runner:
|
|||||||
print(f" Reducing... {k:,}", end = "\r")
|
print(f" Reducing... {k:,}", end = "\r")
|
||||||
|
|
||||||
try:
|
try:
|
||||||
red_type, node = lamb.nodes.reduce(node)
|
red_type, node = lamb.node.reduce(node)
|
||||||
except KeyboardInterrupt:
|
except KeyboardInterrupt:
|
||||||
stop_reason = StopReason.INTERRUPT
|
stop_reason = StopReason.INTERRUPT
|
||||||
break
|
break
|
||||||
|
|
||||||
# If we can't reduce this expression anymore,
|
# If we can't reduce this expression anymore,
|
||||||
# it's in beta-normal form.
|
# it's in beta-normal form.
|
||||||
if red_type == lamb.nodes.ReductionType.NOTHING:
|
if red_type == lamb.node.ReductionType.NOTHING:
|
||||||
stop_reason = StopReason.BETA_NORMAL
|
stop_reason = StopReason.BETA_NORMAL
|
||||||
break
|
break
|
||||||
|
|
||||||
# Count reductions
|
# Count reductions
|
||||||
k += 1
|
k += 1
|
||||||
if red_type == lamb.nodes.ReductionType.FUNCTION_APPLY:
|
if red_type == lamb.node.ReductionType.FUNCTION_APPLY:
|
||||||
macro_expansions += 1
|
macro_expansions += 1
|
||||||
|
|
||||||
if k >= self.iter_update:
|
if k >= self.iter_update:
|
||||||
@ -178,7 +213,7 @@ class Runner:
|
|||||||
("class:text", str(node)), # type: ignore
|
("class:text", str(node)), # type: ignore
|
||||||
]
|
]
|
||||||
|
|
||||||
self.history.append(lamb.nodes.expand(node, force_all = True)[1])
|
self.history.append(lamb.node.expand(node, force_all = True)[1])
|
||||||
|
|
||||||
|
|
||||||
printf(
|
printf(
|
||||||
@ -218,7 +253,7 @@ class Runner:
|
|||||||
|
|
||||||
# If this line is a command, do the command.
|
# If this line is a command, do the command.
|
||||||
elif isinstance(e, Command):
|
elif isinstance(e, Command):
|
||||||
if e.name not in cmd.commands:
|
if e.name not in lamb.commands.commands:
|
||||||
printf(
|
printf(
|
||||||
FormattedText([
|
FormattedText([
|
||||||
("class:warn", f"Unknown command \"{e.name}\"")
|
("class:warn", f"Unknown command \"{e.name}\"")
|
||||||
@ -226,10 +261,10 @@ class Runner:
|
|||||||
style = lamb.utils.style
|
style = lamb.utils.style
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
cmd.commands[e.name](e, self)
|
lamb.commands.commands[e.name](e, self)
|
||||||
|
|
||||||
# If this line is a plain expression, reduce it.
|
# If this line is a plain expression, reduce it.
|
||||||
elif isinstance(e, lamb.nodes.Node):
|
elif isinstance(e, lamb.node.Node):
|
||||||
self.reduce(e, status = o)
|
self.reduce(e, status = o)
|
||||||
|
|
||||||
# We shouldn't ever get here.
|
# We shouldn't ever get here.
|
@ -1,2 +0,0 @@
|
|||||||
from .runner import Runner
|
|
||||||
from .runner import StopReason
|
|
@ -1,42 +0,0 @@
|
|||||||
import enum
|
|
||||||
import lamb
|
|
||||||
|
|
||||||
class StopReason(enum.Enum):
|
|
||||||
BETA_NORMAL = ("class:text", "β-normal form")
|
|
||||||
LOOP_DETECTED = ("class:warn", "Loop detected")
|
|
||||||
MAX_EXCEEDED = ("class:err", "Too many reductions")
|
|
||||||
INTERRUPT = ("class:warn", "User interrupt")
|
|
||||||
SHOW_MACRO = ("class:text", "Displaying macro content")
|
|
||||||
|
|
||||||
class MacroDef:
|
|
||||||
@staticmethod
|
|
||||||
def from_parse(result):
|
|
||||||
return MacroDef(
|
|
||||||
result[0].name,
|
|
||||||
result[1]
|
|
||||||
)
|
|
||||||
|
|
||||||
def __init__(self, label: str, expr: lamb.nodes.Node):
|
|
||||||
self.label = label
|
|
||||||
self.expr = expr
|
|
||||||
|
|
||||||
def __repr__(self):
|
|
||||||
return f"<{self.label} := {self.expr!r}>"
|
|
||||||
|
|
||||||
def __str__(self):
|
|
||||||
return f"{self.label} := {self.expr}"
|
|
||||||
|
|
||||||
def set_runner(self, runner):
|
|
||||||
return self.expr.set_runner(runner)
|
|
||||||
|
|
||||||
class Command:
|
|
||||||
@staticmethod
|
|
||||||
def from_parse(result):
|
|
||||||
return Command(
|
|
||||||
result[0],
|
|
||||||
result[1:]
|
|
||||||
)
|
|
||||||
|
|
||||||
def __init__(self, name, args):
|
|
||||||
self.name = name
|
|
||||||
self.args = args
|
|
@ -1,7 +1,5 @@
|
|||||||
from prompt_toolkit.styles import Style
|
from prompt_toolkit.styles import Style
|
||||||
from prompt_toolkit.formatted_text import HTML
|
from prompt_toolkit.formatted_text import HTML
|
||||||
from prompt_toolkit.lexers import Lexer
|
|
||||||
from prompt_toolkit.key_binding import KeyBindings
|
|
||||||
from prompt_toolkit import print_formatted_text as printf
|
from prompt_toolkit import print_formatted_text as printf
|
||||||
from importlib.metadata import version
|
from importlib.metadata import version
|
||||||
|
|
||||||
@ -16,11 +14,6 @@ style = Style.from_dict({ # type: ignore
|
|||||||
"code": "#AAAAAA italic",
|
"code": "#AAAAAA italic",
|
||||||
"muted": "#AAAAAA",
|
"muted": "#AAAAAA",
|
||||||
|
|
||||||
# Syntax highlighting colors
|
|
||||||
"syn_cmd": "#FFFFFF italic",
|
|
||||||
"syn_lambda": "#AAAAAA",
|
|
||||||
"syn_paren": "#AAAAAA",
|
|
||||||
|
|
||||||
# Command formatting
|
# Command formatting
|
||||||
# cmd_h: section titles
|
# cmd_h: section titles
|
||||||
# cmd_key: keyboard keys, usually one character
|
# cmd_key: keyboard keys, usually one character
|
||||||
@ -35,46 +28,6 @@ style = Style.from_dict({ # type: ignore
|
|||||||
})
|
})
|
||||||
|
|
||||||
|
|
||||||
# Replace "\" with pretty "λ"s
|
|
||||||
bindings = KeyBindings()
|
|
||||||
@bindings.add("\\")
|
|
||||||
def _(event):
|
|
||||||
event.current_buffer.insert_text("λ")
|
|
||||||
|
|
||||||
# Simple lexer for highlighting.
|
|
||||||
# Improve this later.
|
|
||||||
class LambdaLexer(Lexer):
|
|
||||||
def lex_document(self, document):
|
|
||||||
def inner(line_no):
|
|
||||||
out = []
|
|
||||||
tmp_str = []
|
|
||||||
d = str(document.lines[line_no])
|
|
||||||
|
|
||||||
if d.startswith(":"):
|
|
||||||
return [
|
|
||||||
("class:syn_cmd", d)
|
|
||||||
]
|
|
||||||
|
|
||||||
for c in d:
|
|
||||||
if c in "\\λ.":
|
|
||||||
if len(tmp_str) != 0:
|
|
||||||
out.append(("class:text", "".join(tmp_str)))
|
|
||||||
out.append(("class:syn_lambda", c))
|
|
||||||
tmp_str = []
|
|
||||||
elif c in "()":
|
|
||||||
if len(tmp_str) != 0:
|
|
||||||
out.append(("class:text", "".join(tmp_str)))
|
|
||||||
out.append(("class:syn_paren", c))
|
|
||||||
tmp_str = []
|
|
||||||
else:
|
|
||||||
tmp_str.append(c)
|
|
||||||
|
|
||||||
if len(tmp_str) != 0:
|
|
||||||
out.append(("class:text", "".join(tmp_str)))
|
|
||||||
return out
|
|
||||||
return inner
|
|
||||||
|
|
||||||
|
|
||||||
def show_greeting():
|
def show_greeting():
|
||||||
# | _.._ _.|_
|
# | _.._ _.|_
|
||||||
# |_(_|| | ||_)
|
# |_(_|| | ||_)
|
||||||
|
77
macros.lamb
77
macros.lamb
@ -1,77 +0,0 @@
|
|||||||
# How to use exported files in lamb:
|
|
||||||
#
|
|
||||||
# [Syntax Highlighting]
|
|
||||||
# Most languages' syntax highlighters will
|
|
||||||
# highlight this code well. Set it manually
|
|
||||||
# in your editor.
|
|
||||||
#
|
|
||||||
# Don't use a language for which you have a
|
|
||||||
# linter installed, you'll get lots of errors.
|
|
||||||
#
|
|
||||||
# Choose a language you don't have extenstions for,
|
|
||||||
# and a language that uses # comments.
|
|
||||||
#
|
|
||||||
# The following worked well in vscode:
|
|
||||||
# - Julia
|
|
||||||
# - Perl
|
|
||||||
# - Coffeescript
|
|
||||||
# - R
|
|
||||||
|
|
||||||
# [Writing macros]
|
|
||||||
# If you don't have a custom keyboard layout that can
|
|
||||||
# create λs, you may use backslashes instead.
|
|
||||||
# (As in `T = \ab.b`)
|
|
||||||
#
|
|
||||||
# This file must only contain macro definitons. Commands will be ignored.
|
|
||||||
# Statements CANNOT be split among multiple lines.
|
|
||||||
# Comments CANNOT be on the same line as macro defintions.
|
|
||||||
# All leading whitespace is ignored.
|
|
||||||
|
|
||||||
|
|
||||||
# Misc Combinators
|
|
||||||
M = λx.(x x)
|
|
||||||
W = (M M)
|
|
||||||
Y = λf.((λx.(f (x x))) (λx.(f (x x))))
|
|
||||||
|
|
||||||
|
|
||||||
# Booleans
|
|
||||||
T = λab.a
|
|
||||||
F = λab.b
|
|
||||||
NOT = λa.(a F T)
|
|
||||||
AND = λab.(a b F)
|
|
||||||
OR = λab.(a T b)
|
|
||||||
XOR = λab.((a (NOT b)) b)
|
|
||||||
|
|
||||||
|
|
||||||
# Numbers
|
|
||||||
# PAIR: prerequisite for H.
|
|
||||||
# Makes a two-value tuple, indexed with T and F.
|
|
||||||
#
|
|
||||||
# H: shift-and-add, prerequisite for D
|
|
||||||
#
|
|
||||||
# S: successor (adds 1)
|
|
||||||
#
|
|
||||||
# D: predecessor (subtracts 1)
|
|
||||||
#
|
|
||||||
# Z: tests if a number is zero
|
|
||||||
# NZ: equivalent to `NOT Z`
|
|
||||||
#
|
|
||||||
# ADD: adds two numbers
|
|
||||||
#
|
|
||||||
# MULT: multiply two numbers
|
|
||||||
#
|
|
||||||
# FAC:
|
|
||||||
# Recursive factorial. Call with `Y FAC <number>`
|
|
||||||
# Don't call this with numbers bigger than 5 unless you're very patient.
|
|
||||||
#
|
|
||||||
# `Y FAC 6` required 867,920 reductions and took 10 minutes to run.
|
|
||||||
|
|
||||||
PAIR = λabi.(i a b)
|
|
||||||
H = λp.((PAIR (p F)) (S (p F)))
|
|
||||||
S = λnfa.(f (n f a))
|
|
||||||
D = λn.((n H) ((PAIR 0) 0) T)
|
|
||||||
Z = λn.(n (λa.F) T)
|
|
||||||
NZ = λn.(n (λa.T) F)
|
|
||||||
ADD = λmn.(m S n)
|
|
||||||
MULT = λnmf.(n (m f))
|
|
||||||
FAC = λyn.( (Z n)(1)((MULT n) (y (D n))) )
|
|
@ -14,7 +14,7 @@ description = "A lambda calculus engine"
|
|||||||
#
|
#
|
||||||
# Patch release:
|
# Patch release:
|
||||||
# Small, compatible fixes.
|
# Small, compatible fixes.
|
||||||
version = "0.1.3"
|
version = "0.1.2"
|
||||||
|
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"prompt-toolkit==3.0.31",
|
"prompt-toolkit==3.0.31",
|
||||||
|
Reference in New Issue
Block a user