Package: logipar
Logipar/lɑːdʒɪpɜːr/noun: Your go-to polyglotlogic string parser.verb: Parse that logic string, my friend.What is a logic string parser?Have you ever wanted to filter data based on a string of ANDs and ORs and NOTs?  Well now you can!In fact, that's exactly whatLogiparis here to help you do.If that doesn't help, check out ourCat breeddemo to seeLogiparin action!  Or you can try it yourself onRunkit.Logiparsupports:ANDORNOTXORand ParenthisesYou can rename the operatores however you want!  You can also use it with basically whateverliterals/valuesyou want¹.  (1. There aresomerestrictions.)A simple example:one AND (two OR three)A more complex example:title=Cat XOR title contains dog.Logipardoesn't care about the literals you use, so you can add whatever complexity you is appropriate for your project there - I'm not judging!  In fact,I endorse it.Logipar will automatically merge adjacent literals,unless you don't want it to. Sotitle contains dogcan count as a single literal, even without quotation marks.  Or it can count as threetitle,contains, anddog- the choice is yours! (By default it merges.)What can I do with it once it's parsed?Oh, man, whatever you want really!  You can test objects against the parse tree (using a functionLogiparreturns -see the filtering section).  You can flatten the parse tree to a string of your design (with the help ofLogipar'sstringify()function -see the stringing section).I guess.. I guess that's really all.  But come on, what more do you even want??Okay cool, can I use it though?Logiparis written inHaxe.WAIT DON'T BE SCARED.  All that means for you is it can be (and is) compiled to multiple languages.  Maybe you've heard of one of these before:JavascriptPythonPHPThere are more, but I'm going to focus the examples on those for now.InstallationJavascriptnpm i logiparyarn add logiparOr you can just download and useLogipar.js- say in a<script src="Logipar.js"></scrip>tag.Pythonpip install logiparOr you can just download and useLogipar.pyin your project.PHPBad news.Logiparisn't on Composer.  I probably won't bother to add it there unless someonereallywants it, because ofthis issue.
Good news! You can totally use thisLogipar.pharinstead.  Or, you know, donwload the files directly if you want.Haxehaxelib install logiparAlso the source files arehere.But how do I use it?Great question!  Here are some examples in different languages.UsageJavascriptYou can follow along with these javascript samples on  onRunkit.constlogipar=require("logipar")constlp=newlogipar.Logipar();lp.parse("a AND b");console.log(lp.toString())Or you can includeLogipar.jsin your code.  Note that in this method the classes are accessed viaLogipar,Token, andNode- rather than through alogiparconstant, as above.<scriptsrc="Logipar.js"></script>// Include the library however works for you.  You can see how I did it in js_sample.htmlvarlp=newLogipar();lp.parse("a AND b");console.log(lp.stringify());Pythonimportlogiparlp=logipar.Logipar()lp.parse("a AND b")print(lp.toString())PhpWhen you're using the PHAR, it should take care of loading the classes for you.require_once("Logipar.phar");$lp = new \logipar\Logipar();$lp->parse("a AND b");print($lp->toString());Quotations marksWhileLogiparcan automatically merge neigbouring literals, sometimes that's not enough.  It also supports quotation marks around literals.  This means you can have values that would otherwise be parsed as tokensinthe literals - if they're wrapped in quotation marks.  The quotation marks become part of the value, for you to deal with however you want.  This is also handy for supplying whitespace as a value.
Take the logic stringa="CAT OR DOG" OR This is a sentance..a="CAT OR DOG"is a literal.  Even though it has and an OR in it.  You can then use it however is appropriate - split it on the equals sign maybe, and strip the quotation marks to check for the string "CAT OR DOG" in the "a" column.  I don't know, that's your journey!This is a sentance.is also a literal since it'll be automatically merged by default.Logipar'smergeAdjacentLiterals(which defaults totrue) controls this. So set it to false if you don't want to merge them.So it'll parse out to:a="CAT OR DOG"ORThis is a sentance..The default quotation mark characters are"and'.  But you can add to or change these throughLogipar's aptly-namedquotationsproperty - which is an array of strings denoting whatever you want to use as valid quotation mark characters.Javascriptlp.quotations.push("`");// Add backticklp.mergeAdjacentLiterals=true;// This is its default valuePythonlp.quotations.append("`");//Addbackticklp.mergeAdjacentLiterals=true;//ThisisitsdefaultvaluePhp$lp->quotations[] = "`"; // Add backtick$lp->mergeAdjacentLiterals = true; // This is its default valueCase sensitivityBy default theLogipar's operators are case-sensitive, but they don't have to be.  Simply change thecaseSensitiveproperty tofalse, and YoU cAn TyPe ThEm HoWeVeR yOu Want!Javascriptlp.caseSensitive=false;Pythonlp.caseSensitive=False;Php$lp->caseSensitive = false;Custom operatorsYou can also replace the default strings for any or all oflogipar's operators.  Maybe you want to go the old^ vroute.  Or maybe&&and||.  Or even just+and*.  I don't know what you want!
Valid operators are:Token.ANDdefault:ANDToken.ORdefault:ORToken.XORdefault:XORToken.NOTdefault:NOTToken.OPENdefault:(Token.CLOSEdefault:)You should probably keep theOPENandCLOSE(parentheses) operators as single characters, unless you want to enforce whitespace between all tokens tokens.Javascriptlp.overwrite(logipar.Token.AND,"&&");Pythonlp.overwrite(logipar.logipar_Token.AND,"et")PhpPHP is a little more problematic.AND,ORandXORare keywords in it, which makes it difficult to access those Token constants.  Rather than rename those variables, you can just use the string values. (You can do the same with the other ones, if you really want to -all the string values are the same as the constant afterToken..)$lp->overwrite("AND", "et");StringificationSometimes you want your logic tree flattened; pressed firmly into a string.  Maybe you just want to display it, or maybe you'd like to use it in your SQL. I don't know - and I'm not judging.Logiparshould provide for all your stringifying needs with it'sstringify()function.
When you callstringify, you have the option of passing a function to it - this function is used to convert nodes to strings in any manner you like.  It will be called on each node in the tree.  Anything you don't account for will use the defaulttoString()function provided byLogipar.That's confusing right?  Well here, take a look at this function in Haxe:functionmystringer(n:logipar.Node):String{if(n.token.type==logipar.Token.XOR){return"(("+n.f(n.left)+" AND NOT "+n.f(n.right)+") OR (NOT "+n.f(n.left)+" AND "+n.f(n.right)+"))";}returnnull;}There are some things going on there.  Definite things.  Let's start with the signature:  Your function should take alogipar.Nodeas a param, and return aString.Say whatever we're using doesn't support anXORoperation.  That's okay,a XOR bis just a fancy way of saying(a AND NOT b) OR (NOT a AND b).  We can handle that.
First, we need to know if this is the type of node we want to change (XOR), so we check if the node passed in (n) is currently of typelogipar.Token.XOR.  Then we just return the string the way we want it.  In this case:return "((" + n.f(n.left) + " AND NOT " + n.f(n.right) + ") OR (NOT " + n.f(n.left) + " AND " + n.f(n.right) + "))";But wait.  What's going on there?   WellXORnodes (and all binary nodes) haveleftandrightproperties, representing their preceeding and succeeding operands. (Unary nodes likeNOTonly have arightproperty; or rather,leftwill be null.)  So we're just saying:(({LEFT} AND NOT {RIGHT}) OR (NOT {LEFT} AND {RIGHT}))With one added wrinkle.  Theleftandrightproperties are nodes themselves.  They may containXORs of their own.  So we want to recursively call the same stringification function on them.f()is a helper function available for the duration of the stringification process for this very purpose.  That's why you seen.f(n.left)above.Thereturn null;letsLogiparknow it should display any other node as usual.  So in this case, anything that's not anXORgets displayed as it normally would.Javascriptvarstr=lp.stringify(function(n){if(n.token.type==logipar.Token.XOR)return"(("+n.f(n.left)+" AND NOT "+n.f(n.right)+") OR (NOT "+n.f(n.left)+" AND "+n.f(n.right)+"))";returnnull;});PythondefexpandXOR(n):ifn.token.type==logipar.logipar_Token.XOR:l=n.f(n.left)r=n.f(n.right)return"(({}AND NOT{}) OR (NOT{}AND{}))".format(l,r,l,r)returnNoneflattened=lp.stringify(expandXOR)PhpNote that again I'm just using the string "XOR" in PHP.  Also, I'm usingcall_user_functo call$n->f()on the child nodes.$flattened = $lp->stringify(function($n) {if ($n->token->type == "XOR") {$l = call_user_func($n->f, $n->left);$r = call_user_func($n->f, $n->right);return "((" . $l . " AND NOT " . $r . ") OR (NOT " . $l . " AND " . $r . "))";}return null;});The string returned will make use if minimal parentheses.  If for some reason you want everything wrapped in brackets, that's easy too:lp.walk(function(n:logipar.Node):Void{n.bracketing=logipar.Node.MAXIMAL_BRACKETS;});That'll set the bracketing mode for each node in the tree toMAXIMAL_BRACKETS.  If you only want to change certain node types, you can check the value inn.token.typeand act accordingly.Filtering dataSometimes you just want to filter an array of rows. Nothing more, nothing less.  Well, maybe more.  Maybe you want to do it based ona logic string.Logipar'sfilterFunctioncan help.  It creates a function you can use to filter your data.  But how does it work?  You handle the leaves, and we'll handle the logic tree.Basically, you just need to decide if a given leaf resolvestrueorfalsefor a given row of data.  And then we'll figure out if it matches overall.Here's an example in Haxe:varleafresolver=function(row:Dynamic,value:String):Bool{// This is  just checks a leaf node (value) against every column in the data (row), in a case-insensitive way.// But you can get as complex as you'd like and parse the value variable however you like.for(finReflect.fields(row)){// For each property of rowif(Std.string(Reflect.field(row,f)).toLowerCase().indexOf(value.toLowerCase())!=-1)// If that property contains the leafreturntrue;}returnfalse;}varmyfilter:(Dynamic)->Bool=ls.filterFunction(leafresolver);Okay, so you can see above thatLogipar'sfilterFunction()takes a function as its argument, and returns a function.  The first function (leafresolver()) we supply, the second we use to actually do our filtering.leafresolvertakes arowof data.  This is probably an object of some sort, but that's your journey.  For the sake of our example, let's say it's{title: "Harry potter", "author": "J.K. Rowling"}.
It also takes a stringvalue.  This is the value of the leaf we're checking.  For the sake of our example,harry.The task of this function is to takevalueand see if it matches forrow.  You can do this however you want.  This function is then run on everyLITERAL(the leaves of the logic tree), and we use its result to decide if the logic tree resolves totrueorfalseforrow.For this example, it'd checkHaragainst each property inrow:title, andauthor.  Since the title isHarry Potter, and we've specified in the function to convert to lowercase before checking, it'll match and returntrue.filterFunctionreturns a function, whcih you can then  use on your data. For example,myfilter(data[i])will returntrueorfalsedepending on if it matches the logic of the query.That's still pretty confusing, but hopefully some more examples will clear it up.Javascriptfunctionleafresolver(row,value){// This is  just checks the values against every column, in a case-insensitive wayfor(varfieldinrow)if(row[field].toString().toLowerCase().includes(value.toLowerCase()))returntrue;returnfalse;}f=lp.filterFunction(leafresolver);filtered_data=sample_data.filter(f);// Javascript arrays have a filter functionPythondefleafresolver(row,value):# This is  just checks the values against every column, in a case-insensitive wayforfieldinrow:ifvalue.lower()instr(row[field]).lower():returnTruereturnFalsef=lp.filterFunction(leafresolver)data=list(filter(f,data))# Python has a filter function tooPhp$leafresolver = function($row, $value) {foreach($row as $field=>$v)if (stripos($row[$field], $value) !== false)return true;return false;};$f = $lp->filterFunction($leafresolver);$data = array_filter($data, $f);    // Oh look, so does PHPNow, let's try a more complex example in Haxe:varf=ls.filterFunction(function(row:Dynamic,value:String):Bool{value=value.replace('"','');// Strip out the quotation marksif(value.indexOf(":")==-1){// If there's no colon, just check if the value exists in any fieldfor(finReflect.fields(row)){if(Std.string(Reflect.field(row,f)).toLowerCase().indexOf(value.toLowerCase())!=-1)returntrue;}}else{// There was a colon.  Let's split it into field:value.varchunks=value.split(':');varfield=chunks.shift();// The field is before the first colonvarval=chunks.join(':');// Any subsequent colons should be part of the value we look forif(Reflect.hasField(row,field)){// If that field exists, check if the value is in itif(Std.string(Reflect.field(row,field)).toLowerCase().indexOf(val.toLowerCase())!=-1)returntrue;}}returnfalse;});What this function does is it allows for values in the formatcolumn:valueand then checks ifvalueexists in that column.  For example, a logic string we might support could be:title:harry and not "and".  This filter function will resolve true for any entries where:the title column contains "harry" (case-insensitive)the string "and" is not in any of the columns (case-insensitive)To see some more filtering examples, check out:docs/filters.md.The endThat's all for now.  Happy parsing!