Mathics3 / mathics-core

An open-source Mathematica. This repository contains the Python modules for WL Built-in functions, variables, core primitives, e.g. Symbol, a parser to create Expressions, and an evaluator to execute them.
https://mathics.org
Other
782 stars 48 forks source link

Mathics crash running `MatchQ[0 + x, ( a_. + b_. ) ]` #1173

Open rocky opened 1 week ago

rocky commented 1 week ago

Description

MatchQ[0 + x, ( a_. + b_. ) ]

produces a Python traceback.

How to Reproduce

$ mathics
In[1]:=  MatchQ[0 + x, ( a_. + b_. ) ]
Traceback (most recent call last):
  File "/home/rocky/.pyenv/versions/3.12.7/bin/mathics", line 33, in <module>
    sys.exit(load_entry_point('Mathics3', 'console_scripts', 'mathics')())
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Expected behavior

No crash. For the example given, True is expected.

Additional context

This was encountered in working on getting Rubi running. See also https://github.com/Mathics3/mathics-core/discussions/1168#discussioncomment-11298819

rocky commented 1 week ago

When I just tried it now, I am not seeing a crash. There is probably something more to this that needs to be worked out. Perhaps it is the lack of wrapping 0 + x in Hold[] and there is some particular value of x that causes a problem?

mmatera commented 1 week ago

Notice that also the pattern must be wrapped in Hold[...]. Otherwise, the match fails at the level of the Hold head.

rocky commented 1 week ago

Whether or not the pattern is wrapped in Hold[...], Mathics should not crash.

aravindh-krishnamoorthy commented 6 days ago

In function: https://github.com/Mathics3/mathics-core/blob/bf6a8c0153170b1350f7ed00792eaa4ac801813a/mathics/core/pattern.py#L668-L672 the pattern a_. + b_. causes self.elements to be:

In[1]:= MatchQ[x, a_. + b_.]
> ~/git/mathics/mathics-core/mathics/core/pattern.py(760)match_expression_with_one_identity()
-> assert new_pattern is not None
(Pdb) new_pattern
(Pdb) self
<ExpressionPattern: System`Plus[System`Optional[System`Pattern[Global`a, System`Blank[]]], System`Optional[System`Pattern[Global`b, System`Blank[]]]]>
(Pdb) self.elements
[<mathics.builtin.patterns.defaults.Optional object at 0x7ff543d16190>, <mathics.builtin.patterns.defaults.Optional object at 0x7ff543e7ef50>]
(Pdb)

both of which are Optional. Hence, new_pattern is not set, eventually leading to the assertion failure: https://github.com/Mathics3/mathics-core/blob/bf6a8c0153170b1350f7ed00792eaa4ac801813a/mathics/core/pattern.py#L758