Skip to content

feat(formula): parse boolean formulae - #53

Draft
Trosper3 wants to merge 86 commits into
ReduxISU:mainfrom
Trosper3:feat/44-boolean-formulae
Draft

Trosper3 wants to merge 86 commits into
ReduxISU:mainfrom
Trosper3:feat/44-boolean-formulae

Conversation

@Trosper3

Copy link
Copy Markdown
Contributor

Lets a definition declare a part as a boolean formula, so SAT-style instances can be checked and read by SPADE.

Stacked on #28: review only the last three commits; the diff shrinks as #13–#28 merge.

Features

  • x is formula and x is cnf check that a part is a boolean formula, or one in conjunctive normal form, with a clear failure like Constraint phi is cnf failed: ... (Part/Element set, the formula's own error kept inside).
  • Formula.Parse / Formula.ParseCnf read a formula into a tree (Variable, Not, And, Or) with Variables, Evaluate, IsCnf, ToClauses() and a canonical ToString() that reads back the same.
  • Same syntax as Redux's CNF parser (Replace SAT/3SAT string-splitting parser with a CNF lexer/parser Redux#788): !, &, |, parentheses and the same variable names, so every formula Redux accepts today reads the same here, and every one it rejects is rejected. Checked with Redux's own parser tests and 2,000,000 random inputs, with no differences.
  • General formulas use the usual precedence ! > & > | with any nesting, as Add general-formula SAT with a Tseitin reduction to (CNF) SAT Redux#856 needs. x1 | x2 & x3 reads as x1 | (x2 & x3) there, while CNF still rejects it as Redux does.
  • No crashes on deep nesting (Parsing is slow on large input and crashes the process on deep nesting #7): a formula nests at most 256 levels; deeper input gets a parse error instead of a stack overflow.
  • Docs: new Documentation/Formula.md, plus the type in DefinitionString.md and example.md.

Notes

  • formula and cnf are read as plain words, so the ANTLR grammar didn't need regenerating, and x in formula still means a part named formula.
  • In an instance, a formula with ( or , must be quoted ("(x1 | !x2) & x3"), using feat(grammar): add an is string type check, with quoted values #27's quoted values. Redux can call Formula.ParseCnf directly on its existing bare SAT strings.
  • No true/false constants or -> yet, as #856 suggests for a first step.

Testing

134 new tests (431 in all, passing): Redux's CNF cases, precedence against truth tables, round-trips, equality, depth limits, and formulas inside definitions.

Issue Handling

Since d7e982e, an unorderedcross membership check rejected every
normal undirected edge such as {a,b}. The added line checked whether
each node inside the edge was a list, and plain nodes never are.

The check now looks at the edge itself: a plain value is not an
edge, so it fails the constraint instead of crashing while being
enumerated. List edges such as (a,b) are still accepted, as in the
released 0.1.2, because existing grammars for directed graphs rely
on it.

Closes ReduxISU#12
An unorderedcross member is an unordered pair, so it must be a set
such as {a,b}. A list such as (a,b) is an ordered pair, which is what
cross describes, so it is now rejected here too. This is what
d7e982e set out to do.

Grammars for directed graphs that use unorderedcross with list edges
need to switch to cross.

Refs ReduxISU#12
"N is int" checked nothing at all: int reaches the constraint as a set
descriptor, and the "is" branch only handled the set, list and int
keywords. So abc, {1} and (1,2) all passed. It now requires a single
value that parses as an integer.

"S is set" accepted a plain value, because a value is not ordered. It
now requires an unordered collection.

"is list" already rejected values and sets; it is now covered by tests.

Closes ReduxISU#10
Replaces the substring-based reader in UtilCollection(string) with
InstanceScanner, which walks the input once.

Whitespace (ReduxISU#2): spaces, tabs and line breaks around { } ( ) , and at
either end of the input are skipped, so {2, 3} now holds 3 and a
trailing new line no longer breaks an instance. Inside a value,
whitespace next to [ ] ; : = is dropped, plain spaces are kept (New
York), and a run with a tab or line break becomes one space. These
match the rules Redux applies before parsing today.

Errors (ReduxISU#4): malformed input throws SpadeParseException with the
position, what was expected and what was found, e.g. "expected , or }
at position 5, found end of input" for {1,2. Input that used to be
misread without an error, such as {1,2 or {1,2}junk, is now rejected.

Time and depth (ReduxISU#7): parsing is linear in the input's length, and
ToString builds its text in one buffer. Nesting deeper than 256 levels
is rejected instead of overflowing the stack and crashing the process.
40,000 elements took 104 seconds before; 100,000 now take well under
a second.

Closes ReduxISU#2
Closes ReduxISU#7
Refs ReduxISU#4
…tion

Input that is well formed but doesn't fit the definition string threw
whatever happened to fail: InvalidOperationException ("Cannot index
into a set"), ArgumentOutOfRangeException, or a bare Exception whose
message said PLACEHOLDER. All of these now throw SpadeParseException
with a message that names what failed:

- A format such as (N,E) checks that it got a list of exactly that
  many elements. A longer list used to be accepted and the extra
  elements dropped.
- Constraint failures quote the constraint as written, e.g.
  "Constraint E subset N unorderedcross N failed: {1,9} is not a
  member". Long values are shortened.
- subset on a plain value, and cross on anything that isn't a pair,
  fail the constraint instead of crashing.

Closes ReduxISU#4
A set drops repeated elements, so {3,3,2,2} was read as {3,2}. Problems
defined on multisets, such as Partition and Subset Sum, then solved a
different instance from the one written.

A definition string can now mark a collection with "is multiset":

    {N | N is multiset, N subset int}

reads {3,3,2,2} as four numbers. It applies before the other
constraints wherever it is written. Without it, braces still mean a
set, so nothing changes for existing definitions or callers.

To make this possible, a set read from an instance string keeps its
elements as written, and AsMultiset() turns them into a multiset.
Multisets count every occurrence in Count(), enumeration and
ToString(), compare by count in any order, and have order-independent
hash codes. Union and Intersect use the larger and smaller count. New
CountOf() and IsSubsetOf() compare by count, so {7,7} is in {7,7,1}
but not in {7,1}. A set and a multiset are never equal, and "is set"
rejects a multiset.

Adds the multiset keyword to coll.g4; the lexer is regenerated with
ANTLR 4.13.2, the version that generated the existing files.

Closes ReduxISU#1
…stance

StringParser.Definition reads the definition string on first use and returns
its outline and each named part's kind, object, path and constraints, so a
caller can build an editor for a problem before any instance exists.
…xception

SpadeParseException gets Part, Element, MissingValue and ExpectedIn, so a
caller can find the part an error belongs to without reading the message.
Failures inside a nested set belong to the outer part and member. Messages
are unchanged.

Closes ReduxISU#19
"x is int", "S subset int" and UtilCollection.parseInt used the machine's culture, so a culture with another minus sign could refuse "-5". They now share IntValue, which parses with CultureInfo.InvariantCulture as NumberValue does for number (ReduxISU#23).
Whitespace only: dotnet format SPADE.slnx on this branch's code.
Whitespace only: dotnet format SPADE.slnx on this branch's code.
Whitespace only: dotnet format SPADE.slnx on this branch's code.
Whitespace only: dotnet format SPADE.slnx on this branch's code.
Whitespace only: dotnet format SPADE.slnx on this branch's code.
Whitespace only: dotnet format SPADE.slnx on this branch's code.
Multisets go through the same Add guard, so a hashed multiset can't
change its occurrences or counts. FromSetItems now copies the item list it
keeps as the set's occurrences instead of holding the caller's list.

Tests cover a hashed multiset refusing Add, its elements freezing as they
go in, AsMultiset still working on a frozen set, and unhashed multisets
changing freely.
# Conflicts:
#	Documentation/utilcollection.md
StringParser kept ANTLR's default error listener on the definition
string, which printed the error to the console and recovered with a best
guess, so "{N | N is set" (missing brace), "{N | N is set#}" and
"{N | N is set}}" were accepted. ReduxISU#4 rules out best-guess parsing, and
Definition already rejected the same strings.

The throwing listener moves out of DefinitionDescription into its own
internal class, with one Parse method both use. The StringParser
constructor now reads the definition string through it, so a malformed
one throws the same FormatException as Definition, naming the string and
the position of the first error, before any instance is parsed. Nothing
is printed. parse() walks the tree read at construction instead of
reading the definition string again on every call.
Formula.Parse reads general formulas with ! > & > | and any nesting;
Formula.ParseCnf reads CNF with the rules of Redux's CnfParser, so every
formula Redux accepts reads to the same clauses and every one it rejects
is rejected at the same place (positions count from 1, Redux's from 0).

The tree is Variable, Not, And and Or (chains of one operator are one
node), with Variables, Evaluate, IsCnf, ToClauses and a canonical
ToString that reads back to an equal formula. Nesting is capped at
MaxDepth (256), so deep input is a SpadeParseException, not a stack
overflow (ReduxISU#7).

Part of ReduxISU#44.
"phi is formula" and "phi is cnf" check that a part is a single value
that reads as a formula, or as CNF. A failure names the part like any
failed constraint, and keeps the formula's syntax error, with its
position, as the inner exception. DefinitionDescription reports the
parts as PartKind.Formula and PartKind.Cnf.

The words are plain TERMs to the ANTLR grammar, matched in codeGen and
DefinitionDescription, so the generated parser is unchanged.

Part of ReduxISU#44.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Parse boolean formulae

1 participant