Coder Social home page Coder Social logo

supposedly / nutshell Goto Github PK

View Code? Open in Web Editor NEW
16.0 3.0 4.0 21.33 MB

[alpha!] [dormant!] An advanced cellular-automaton-specification language that transpiles to Golly's.

License: GNU General Public License v3.0

Python 100.00%
cellular-automata esolang conway conway-life esoteric-language golly cellular-automaton

nutshell's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

nutshell's Issues

Restructure class directories

Bunching verything up in magic/common/classes.py isn't too good a look. common should instead only contain 'errors.py' with TabelException & co, and each .py file in segment_types should instead be a directory, containing the main file alongside as many 'classes' files as necessary, whose __init__.py would be from <mainfile> import *.

e.g.

current:

magic/
  common/
    classes/
        cls.py
        errors.py
        napkins.py
  segment_types/
    colors.py
    icons.py
    table.py

proper:

magic/
  common/
    errors.py
  segment_types/
    colors/
      __init__.py
      classes.py
      main.py
    icons/
      __init__.py
      classes.py
      icons_.py
      utils.py
    table/
      __init__.py
      classes.py
      icons_.py
      main.py
      utils.py

(or something)

Switch to Lark for parsing

A rudimentary grammar has been written to nutshell/segment_types/table/lark/grammar.lark, but it's rather hacky and not exactly confidence-inspiring overall. Switching to a Lark grammar proper (over the current hodgepodge of regex) will open the door to a lot of cool new stuff and more reliability overall.

Meta-issue for new syntax additions and/or features

  • Delayed auxiliary transitions: Rare to find a use case, but allow something along the lines of a +N "operation" in an auxiliary to signify that it should take place only after N generations (the compiler would then step through the table to locate the appropriate cellstates that would result from allowing cells in that neighborhood to evolve untouched for N ticks).
    For example, in Brainfuck, the E part of the line WEST_POINTER, W L_BRACK, NW..SE any, S (L_BRACK, prgm), SW any; [S: (BLANK_2, pointerOps)] -> W:L_BRACK E[S: (NORTH_R_BRACK, _, ...)] caused issues because a westbound pointer traveling over an L-bracket but not stopping at it would cause a NORTH_R_BRACK to be born. One solution is to remove the E and phrase it as another line, any, SW L_BRACK, W BLANK_2, NW..S any; NORTH_R_BRACK to indicate that the transition should take place only after the transition from WEST_POINTER -> BLANK_2 has occurred... but it could be expressed more concisely as a modification to the original line to the tune of WEST_POINTER, W L_BRACK, NW..SE any, S (L_BRACK, prgm), SW any; [S: (BLANK_2, pointerOps)] -> W:L_BRACK E+1[S: (NORTH_R_BRACK, _, ...)].
  • Bringing custom symmetries into Nutshell itself: Currently this requires a Python extension class, but it could totally be specified in the table itself. Two big parts of it are Calcyman's suggestion from a while ago to the Golly Gang for indicating symmetries by specifying what napkins are to be equivalent, and BlinkerSpawn's symmetry: notation for specifying which neighbor pairs the ~ operator permutes on.

Random crashing when compiling rule

Github actions run: https://github.com/dragoncoder047/wiki/runs/6294632444?check_suite_focus=true#step:5:46
Nutshell file: https://github.com/dragoncoder047/wiki/blob/deadc2fc9702ebc98649487d18e433b8c1ef035e/Fusion.ruel

Traceback (most recent call last):
  ... 4 frames omitted ...
  File "/opt/hostedtoolcache/Python/3.9.12/x64/lib/python3.9/site-packages/nutshell/main.py", line 60, in _main
    for val in res:
  File "/opt/hostedtoolcache/Python/3.9.12/x64/lib/python3.9/site-packages/nutshell/main.py", line 33, in _transpile
    finished = transpile(infp, find=args.find)
  File "/opt/hostedtoolcache/Python/3.9.12/x64/lib/python3.9/site-packages/nutshell/main.py", line 19, in transpile
    parsed = segmentor.parse(fp)
  File "/opt/hostedtoolcache/Python/3.9.12/x64/lib/python3.9/site-packages/nutshell/segmentor.py", line 66, in parse
    segments[label] = converter(seg, seg_lno, **(annot and {'dep': [segments.get(i) for i in annot]}))
  File "/opt/hostedtoolcache/Python/3.9.12/x64/lib/python3.9/site-packages/nutshell/segment_types/table/table.py", line 111, in __init__.<listcomp>
    self.final = [new_tr for tr in self._data for new_tr in tr.in_symmetry(MinSym)]
  File "/opt/hostedtoolcache/Python/3.9.12/x64/lib/python3.9/site-packages/nutshell/segment_types/table/_classes.py", line 376, in in_symmetry.<listcomp>
    return [self.fix_final([initial, *i, resultant]) for i in distinct(NewSymmetry(j) for j in self.symmetries(napkin).expand())]
  File "/opt/hostedtoolcache/Python/3.9.12/x64/lib/python3.9/site-packages/nutshell/common/utils.py", line 89, in distinct
    if i not in seen:
  File "/opt/hostedtoolcache/Python/3.9.12/x64/lib/python3.9/site-packages/nutshell/segment_types/table/_napkins.py", line 51, in __hash__
    self._hash = hash(tuple(sorted(self.expanded_unique)))
  File "/opt/hostedtoolcache/Python/3.9.12/x64/lib/python3.9/site-packages/nutshell/common/utils.py", line 25, in __get__
    ret = self.method(obj)
  File "/opt/hostedtoolcache/Python/3.9.12/x64/lib/python3.9/site-packages/nutshell/segment_types/table/_napkins.py", line 65, in expanded_unique
    return distinct(self.expanded)
  File "/opt/hostedtoolcache/Python/3.9.12/x64/lib/python3.9/site-packages/nutshell/segment_types/table/_napkins.py", line 158, in expanded
    return (tup for i in self.rotated4() for tup in self.reflection_of(i))
  File "/opt/hostedtoolcache/Python/3.9.12/x64/lib/python3.9/site-packages/nutshell/segment_types/table/_napkins.py", line 78, in rotated4
    return sorted(self.rotate(4))
  File "/opt/hostedtoolcache/Python/3.9.12/x64/lib/python3.9/site-packages/nutshell/segment_types/table/_napkins.py", line 61, in rotate
    return map(self.rotate_by, range(0, len(self), len(self) // n))
ValueError: range() arg 3 must not be zero

Interesting how the commit hash starts with dead, because that's what Nutshell is. I have no idea why Nutshell crashed and need a little help fixing my ruel file if the problem is in there.

Mapping to an ad-hoc variable sometimes breaks

This cropped up while I was working on the RockPaperScissors rueltabel, but I wasn't able to isolate it. Sometimes, when an ad-hoc variable is mapped to, its name in the .rule output will be trimmed from _(\d{15})_\d+ to an integer object (not str!) with the first 14 digits of that capture group. This isn't good!

(Can be avoided for the time being by not mapping to ad-hoc variables and instead declaring them at the top. Annoying, but fortunately the bug is easy to spot if it does occur because Golly will raise a "state out of bounds" error)

Explicitly allow subtraction chains

Currently there is this:

def _subtract_var(self, subt, minuend):
    """
    subt: subtrahend
    minuend: minuend
    """
    try:
        match = int(minuend)
    except ValueError:
        match = tuple(i for i in subt if i not in self._parse_variable(minuend))
    else:
        if match > int(self.directives['n_states']):
            raise ValueError('negated value greater than n_states hm')
        match = tuple(i for i in subt if i != match)
    self.vars[Variable.random_name()] = match
    return match

def _parse_variable(self, var: str, *, mapping=False, ptcd=False):
    """
    var: a variable literal

    return: var, but as a tuple with any references substituted for their literal values
    """
    if var.isalpha() or var.startswith('_'):
        return self.vars[var]
    if var.count('-') == 1:
        # Subtraction & negation (from live states)
        subt, minuend = map(str.strip, var.split('-'))  # Don't *think* I need to strip bc can't have spaces anyway
        subt = self._parse_variable(subt) if subt else self.vars['live']
        return self._subtract_var(subt, minuend)
    if var.startswith('--'):
        # Negation (from all states)
        return self._subtract_var(self.var_all, var.lstrip('-'))
    ...

Notice that _parse_variable() calls _subtract_var() which itself calls _parse_variable() again on the minuend. If it were instead phrased as something like

def _parse_variable(self, var: str, *, mapping=False, ptcd=False):
    """
    var: a variable literal

    return: var, but as a tuple with any references substituted for their literal values
    """
    if var.isalpha() or var.startswith('_'):
        return self.vars[var]
    if var.startswith('--'):
        # Negation (from all states)
        return self._subtract_var(self.var_all, var[2:])
    if '-' in var:
        # Subtraction & negation (from live states)
        subt, minuend = map(str.strip, var.split('-'))  # Don't *think* I need to strip bc can't have spaces anyway
        subt = self._parse_variable(subt) if subt else self.vars['live']
        return self._subtract_var(subt, minuend)
    ...

(i.e. not limiting the amount of - allowed in the minuend)

...then it would open the door for constructs like foo-bar-(1..3), which would effectively be read as foo - (bar - (1..3)) or every state in foo that is not in 'bar without states 1-3', and as many subtractions as necessary (which really shouldn't be more than two, but whatever) will be allowed.

[do tonight when you get home]

Figure out mapping & binding

N..E (1, 2, 3), [N: (3, 2, 1)]
# should produce
(1, 2, 3), (1, 2, 3), (1, 2, 3), [N: (3, 2, 1)]
# and then become
1, (1, 2, 3), (1, 2, 3), 3
2, (1, 2, 3), (1, 2, 3), 2
3, (1, 2, 3), (1, 2, 3), 1

and

N..E [(1, 2, 3)], [N: (3, 2, 1)]
# should produce
(1, 2, 3), [N], [N], [N: (3, 2, 1)]
# and then become
1, 1, 3
2, 2, 2
3, 3, 1

Currently I have it so that only the latter happens in both scenarios, which I don't think is right. The second stage is properly reached, but then after that the [N] bindings get expanded to their variables too soon, destroying the distinction (and I'm not sure how to fix it without reordering everything -- see the if v == ... listcomp lines)

Add single-CD output map syntax

Right now, something like ..., foo, N[NW] assuming Moore has to be expressed as ..., foo, N[NW: foo]. This is suboptimal because it results in NW and foo being expanded to individual transitions when the case could easily be handled with a single Golly variable.

Allow intermixing of Moore and vonNeumann neighborhoods

...Previously while I was working on the Fusion rule that caused all the bugs and crashes in #18, I ended up with this error:

Parsing...
  Error in @TABLE, line 93:
      # NoTomeAtAll
      ^^^^^^^^^^^^^^^^^^^^^^^^^
  `neighborhood` directive cannot be reassigned

The Moore and von Neumann neighborhoods overlap, so couldn't Nutshell automatically allow Moore in some places and vN in others, and just fill in the corners on all the vN ones with any automatically when it expands it to the Moore neighborhood in the output rule file?

Also, the error message is wrong either way. It should be:

Parsing...
  Error in @TABLE, line 94:
      neighborhood: von Neumann
      ^^^^^^^^^^^^^^^^^^^^^^^^^
  `neighborhood` directive cannot be reassigned

Some randomly-picked two-byte unicode chars break Golly

Paste this into Golly:

@RULE brek

@TABLE
n_states:2
neighborhood:Moore
symmetries:none

@ICONS
XPM
"15 15 2 2"
".. c #303030"
"Ӏ c #00EEEEE"
"ӀӀӀӀӀӀӀӀӀӀӀӀӀӀӀ"
"ӀӀӀӀӀӀӀӀӀӀӀӀӀӀӀ"
"ӀӀӀӀӀӀӀӀӀӀӀӀӀӀӀ"
"ӀӀӀӀӀӀӀӀӀӀӀӀӀӀӀ"
"ӀӀӀӀӀӀӀӀӀӀӀӀӀӀӀ"
"ӀӀӀӀӀӀӀӀӀӀӀӀӀӀӀ"
"ӀӀӀӀӀӀӀӀӀӀӀӀӀӀӀ"
"ӀӀӀӀӀӀӀӀӀӀӀӀӀӀӀ"
"ӀӀӀӀӀӀӀӀӀӀӀӀӀӀӀ"
"ӀӀӀӀӀӀӀӀӀӀӀӀӀӀӀ"
"ӀӀӀӀӀӀӀӀӀӀӀӀӀӀӀ"
"ӀӀӀӀӀӀӀӀӀӀӀӀӀӀӀ"
"ӀӀӀӀӀӀӀӀӀӀӀӀӀӀӀ"
"ӀӀӀӀӀӀӀӀӀӀӀӀӀӀӀ"
"ӀӀӀӀӀӀӀӀӀӀӀӀӀӀӀ"

Solution: Use two ASCII chars instead of trying to be clever with Unicode, I guess

Variables can be redefined without erroring

So I finally got Fusion.ruel to compile without errors... but then I checked the output and noticed a problem.

Lines 83-91 of the output reference a variable called anyNTAAHead.0, but it was never defined anywhere else in the file, but it was used in the Nutshell file. (It should be var anyNTAAHead.0 = {7,8}.)

What is causing this and how do I fix it?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.