diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..0e259d4 --- /dev/null +++ b/LICENSE @@ -0,0 +1,121 @@ +Creative Commons Legal Code + +CC0 1.0 Universal + + CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE + LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN + ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS + INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES + REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS + PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM + THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED + HEREUNDER. + +Statement of Purpose + +The laws of most jurisdictions throughout the world automatically confer +exclusive Copyright and Related Rights (defined below) upon the creator +and subsequent owner(s) (each and all, an "owner") of an original work of +authorship and/or a database (each, a "Work"). + +Certain owners wish to permanently relinquish those rights to a Work for +the purpose of contributing to a commons of creative, cultural and +scientific works ("Commons") that the public can reliably and without fear +of later claims of infringement build upon, modify, incorporate in other +works, reuse and redistribute as freely as possible in any form whatsoever +and for any purposes, including without limitation commercial purposes. +These owners may contribute to the Commons to promote the ideal of a free +culture and the further production of creative, cultural and scientific +works, or to gain reputation or greater distribution for their Work in +part through the use and efforts of others. + +For these and/or other purposes and motivations, and without any +expectation of additional consideration or compensation, the person +associating CC0 with a Work (the "Affirmer"), to the extent that he or she +is an owner of Copyright and Related Rights in the Work, voluntarily +elects to apply CC0 to the Work and publicly distribute the Work under its +terms, with knowledge of his or her Copyright and Related Rights in the +Work and the meaning and intended legal effect of CC0 on those rights. + +1. Copyright and Related Rights. A Work made available under CC0 may be +protected by copyright and related or neighboring rights ("Copyright and +Related Rights"). Copyright and Related Rights include, but are not +limited to, the following: + + i. the right to reproduce, adapt, distribute, perform, display, + communicate, and translate a Work; + ii. moral rights retained by the original author(s) and/or performer(s); +iii. publicity and privacy rights pertaining to a person's image or + likeness depicted in a Work; + iv. rights protecting against unfair competition in regards to a Work, + subject to the limitations in paragraph 4(a), below; + v. rights protecting the extraction, dissemination, use and reuse of data + in a Work; + vi. database rights (such as those arising under Directive 96/9/EC of the + European Parliament and of the Council of 11 March 1996 on the legal + protection of databases, and under any national implementation + thereof, including any amended or successor version of such + directive); and +vii. other similar, equivalent or corresponding rights throughout the + world based on applicable law or treaty, and any national + implementations thereof. + +2. Waiver. To the greatest extent permitted by, but not in contravention +of, applicable law, Affirmer hereby overtly, fully, permanently, +irrevocably and unconditionally waives, abandons, and surrenders all of +Affirmer's Copyright and Related Rights and associated claims and causes +of action, whether now known or unknown (including existing as well as +future claims and causes of action), in the Work (i) in all territories +worldwide, (ii) for the maximum duration provided by applicable law or +treaty (including future time extensions), (iii) in any current or future +medium and for any number of copies, and (iv) for any purpose whatsoever, +including without limitation commercial, advertising or promotional +purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each +member of the public at large and to the detriment of Affirmer's heirs and +successors, fully intending that such Waiver shall not be subject to +revocation, rescission, cancellation, termination, or any other legal or +equitable action to disrupt the quiet enjoyment of the Work by the public +as contemplated by Affirmer's express Statement of Purpose. + +3. Public License Fallback. Should any part of the Waiver for any reason +be judged legally invalid or ineffective under applicable law, then the +Waiver shall be preserved to the maximum extent permitted taking into +account Affirmer's express Statement of Purpose. In addition, to the +extent the Waiver is so judged Affirmer hereby grants to each affected +person a royalty-free, non transferable, non sublicensable, non exclusive, +irrevocable and unconditional license to exercise Affirmer's Copyright and +Related Rights in the Work (i) in all territories worldwide, (ii) for the +maximum duration provided by applicable law or treaty (including future +time extensions), (iii) in any current or future medium and for any number +of copies, and (iv) for any purpose whatsoever, including without +limitation commercial, advertising or promotional purposes (the +"License"). The License shall be deemed effective as of the date CC0 was +applied by Affirmer to the Work. Should any part of the License for any +reason be judged legally invalid or ineffective under applicable law, such +partial invalidity or ineffectiveness shall not invalidate the remainder +of the License, and in such case Affirmer hereby affirms that he or she +will not (i) exercise any of his or her remaining Copyright and Related +Rights in the Work or (ii) assert any associated claims and causes of +action with respect to the Work, in either case contrary to Affirmer's +express Statement of Purpose. + +4. Limitations and Disclaimers. + + a. No trademark or patent rights held by Affirmer are waived, abandoned, + surrendered, licensed or otherwise affected by this document. + b. Affirmer offers the Work as-is and makes no representations or + warranties of any kind concerning the Work, express, implied, + statutory or otherwise, including without limitation warranties of + title, merchantability, fitness for a particular purpose, non + infringement, or the absence of latent or other defects, accuracy, or + the present or absence of errors, whether or not discoverable, all to + the greatest extent permissible under applicable law. + c. Affirmer disclaims responsibility for clearing rights of other persons + that may apply to the Work or any use thereof, including without + limitation any person's Copyright and Related Rights in the Work. + Further, Affirmer disclaims responsibility for obtaining any necessary + consents, permissions or other rights required for any use of the + Work. + d. Affirmer understands and acknowledges that Creative Commons is not a + party to this document and has no duty or obligation with respect to + this CC0 or use of the Work. diff --git a/README.md b/README.md index 669eb11..b52b14a 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,5 @@ +[![Downloads](https://static.pepy.tech/badge/bffuck)](https://pepy.tech/project/bffuck) [![Downloads](https://static.pepy.tech/badge/bffuck/month)](https://pepy.tech/project/bffuck) [![Downloads](https://static.pepy.tech/badge/bffuck/week)](https://pepy.tech/project/bffuck) + # BFFuck Makes brainfucking easier @@ -100,6 +102,51 @@ or eq(x,) ``` +Macros: +```text +macro $ # Macro with no arguments +CODE +endmacro + +macro $(,,...) # Macro with arguments +CODE +endmacro + +$ # Using a macro with no arguments +$(,,...) # Using a macro with arguments +``` + +Memory: +```text +ptr(a,b) # Store address of a to variable b +ref(a,b) # Store value of address b to variable a +set(a,b) # Set value of address b to a (variable or integer literal) +``` + +Libraries +```text +?libraryname +``` +Includes the library `library name` (with file extension). + +It first searches the library in current directory, and then in the `stdlib` directory in the package. + +There are standard libraries for BFFuck, they are: +* `env.bff` gets size of a "byte" specified by the compiler +* `alloc.bff` allocates memory +* `array.bff` manages memory using arrays +* `rng.bff` a not very decent random number generator + +An example of the `rng.bff` library is here: +```text +?rng.bff +x=0 +while(1) +$rnd(x) +outc(x) +endwhile +``` +Prints random bytes. ### Platform BFFuck is in **pure Python** and therefore it supports any platform. @@ -108,7 +155,7 @@ Programs compiled from BFFuck needs you to have 8 bit cells that wrap. ### Disadvantages BFFuck currently has these disadvantages: -1. It's numbers are 8 bit numbers. +1. It's numbers are 8 bit numbers. You can choose 8-bit, 16-bit or 32-bit numbers using the `byte` keyword argument. But you need to run it on a 8-bit interpreter. REMEMBER: Using numbers with more bits is slower and increases the size of program largely! If you're using 32 bit, remember to use an extremely optimizing interpreter like bffsree! 2. It has some bugs. diff --git a/bffuck.py b/bffuck.py index c85a327..5863e2c 100644 --- a/bffuck.py +++ b/bffuck.py @@ -1,5 +1,56 @@ +import re, os + +multipliers = ["[>++++++++++<-]>", "[<++++++++++>-]<"] +expanders = { + 1: {">": ">", "<": "<", "+": "+", "-": "-", "[": "[", "]": "]"}, + 2: { + ">": ">>>>", + "<": "<<<<", + "+": ">+<+[>-]>[->>+<]<<", + "-": ">+<[>-]>[->>-<]<<-", + "[": ">+<[>-]>[->+>[<-]<[<]>[-<+>]]<-[+<", + "]": ">+<[>-]>[->+>[<-]<[<]>[-<+>]]<-]<", + }, + 4: { + ">": ">>>>>", + "<": "<<<<<", + "+": "+[<+>>>>>+<<<<-]<[>+<-]+>>>>>[<<<<<->>>>>[-]]<<<<<[->>+[<<+>>>>>+<<<-]<<[>>+<<-]+>>>>>[<<<<<->>>>>[-]]<<<<<[->>>+[<<<+>>>>>+<<-]<<<[>>>+<<<-]+>>>>>[<<<<<->>>>>[-]]<<<<<[->>>>+<<<<]]]>", + "-": "[<+>>>>>+<<<<-]<[>+<-]+>>>>>[<<<<<->>>>>[-]]<<<<<[->>[<<+>>>>>+<<<-]<<[>>+<<-]+>>>>>[<<<<<->>>>>[-]]<<<<<[->>>[<<<+>>>>>+<<-]<<<[>>>+<<<-]+>>>>>[<<<<<->>>>>[-]]<<<<<[->>>>-<<<<]>>>-<<<]>>-<<]>-", + "[": "[>>>>+>>>>>+<<<<<<<<<-]>>>>>>>>>[<<<<<<<<<+>>>>>>>>>-]<<<<<[[-]<<<<<+>>>>>]<<<[>>>+>>>>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]<<<<<[[-]<<<<<+>>>>>]<<[>>+>>>>>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]<<<<<[[-]<<<<<+>>>>>]<[>+>>>>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<<<[[-]<<<<<+>>>>>]<<<<<[[-]>", + "]": "[>>>>+>>>>>+<<<<<<<<<-]>>>>>>>>>[<<<<<<<<<+>>>>>>>>>-]<<<<<[[-]<<<<<+>>>>>]<<<[>>>+>>>>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]<<<<<[[-]<<<<<+>>>>>]<<[>>+>>>>>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]<<<<<[[-]<<<<<+>>>>>]<[>+>>>>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<<<[[-]<<<<<+>>>>>]<<<<<]>", + }, +} + + +def _power_series(k, m): + x = int(k) + if not k: + return "" + if not x and len(k) < 2: + return "" + if len(k) < 2: + return "+" * x + top, rest = k[0], k[1:] + return "+" * int(top) + multipliers[m] + _power_series(rest, 1 - m) + + +def power_series(x): + if not x: + return "" + if len(str(x)) & 1: + return _power_series(str(x), 0) + return _power_series(str(x), 0) + "[<+>-]<" + + +def getstr(x): + normal, power = "+" * x, power_series(x) + if len(normal) < len(power): + return normal + return power + + class BFFuck(object): - """Main implemntation of BFFuck, a compiler making brainfucking easier""" + """Main implementation of BFFuck, a compiler making brainfucking easier""" def __init__(self, playfield=15): """Init object, playfield is the number of bytes used for temporary memory, the lesser the playfield is, the faster the final program is, but setting playfield to a number that is too small causes problems, especially if you want to use integer output.""" @@ -9,6 +60,9 @@ def __init__(self, playfield=15): self.mem = playfield # Leftmost unused memory self.stack = [] # Stack for while loop self.ifstack = [] # Stack for if statement + self.ifvarstack = [] + self.whilevarstack = [] + self.haveelse = [] self.playfield = playfield pass @@ -36,7 +90,7 @@ def program(self, code): else: self.bf += self.movptr(self.mem) self.valdict[val] = self.mem - self.mem += 1 + self.mem += 2 if stmt == "inc": self.bf += "," elif stmt == "in": @@ -54,8 +108,17 @@ def program(self, code): + "-]" ) elif stmt.isdigit(): - self.bf += "[-]" - self.bf += "+" * int(stmt) + self.bf += ( + "[-]" + + self.movptr(0) + + getstr(int(stmt)) + + "[" + + self.movptr(self.valdict[val]) + + "+" + + self.movptr(0) + + "-" + + "]" + ) else: if stmt in self.valdict: self.bf += ( @@ -98,7 +161,7 @@ def program(self, code): else: if int(vn): # while(1) is equivalent to while(2), while(3), etc self.valdict["0"] = self.mem - self.mem += 1 + self.mem += 2 self.bf += self.movptr(self.valdict["0"]) + "+[" self.stack.append(self.valdict["0"]) else: # Skip program @@ -107,59 +170,69 @@ def program(self, code): elif code.startswith( "if(" ): # https://esolangs.org/wiki/Brainfuck_algorithms#if_(x)_{_code_} + self.haveelse.append(False) if not (code.endswith(")")): raise Exception("Unmatched bracket") else: vn = code[3:-1] + x, y, z = self.mem, self.mem + 1, self.mem + 2 + self.mem += 6 if not vn.isdigit(): if vn not in self.valdict: raise Exception("Variable not found") else: self.bf += ( - self.movptr(self.playfield - 1) + self.movptr(x) + "[" + "-" + "]" - + self.movptr(self.playfield - 2) + + self.movptr(y) + "[" + "-" + "]" + self.movptr(self.valdict[vn]) + "[" - + self.movptr(self.playfield - 1) + + self.movptr(x) + "+" - + self.movptr(self.playfield - 2) + + self.movptr(y) + "+" + self.movptr(self.valdict[vn]) + "-" + "]" - + self.movptr(self.playfield - 1) + + self.movptr(x) + "[" + self.movptr(self.valdict[vn]) + "+" - + self.movptr(self.playfield - 1) + + self.movptr(x) + "-" - + "]" - + self.movptr(self.playfield - 2) + + "]+" + + self.movptr(y) + "[" ) self.ifstack.append(self.valdict[vn]) + self.ifvarstack.append(x) else: + self.ifvarstack.append(-1) if int(vn): self.ifstack.append(-1) else: self.temp = self.bf - self.stack.append(-2) # Skip program + self.ifstack.append(-2) # Skip program if code == "endif": if not self.ifstack: raise Exception("End if without if") prev = self.ifstack.pop() + x = self.ifvarstack.pop() if prev == -2: self.bf = self.temp + "]" elif prev == -1: pass else: - self.bf += self.movptr(self.playfield - 2) + "[-]]" + if not self.haveelse[-1]: + self.bf += self.movptr(x + 1) + "[-]]" + else: + self.bf += self.movptr(x) + "-]" + self.haveelse.pop() if code == "endwhile": if not self.stack: raise Exception("End while without while") @@ -170,9 +243,13 @@ def program(self, code): self.bf += self.movptr(prev) self.bf += "]" if code == "else": + self.haveelse[-1] = True if not self.ifstack: raise Exception("Else without if") prev = self.ifstack.pop() + x = self.ifvarstack.pop() + y = x + 1 + z = prev if prev == -2: self.bf = self.temp + "]" self.ifstack.append(-1) @@ -180,45 +257,16 @@ def program(self, code): self.temp = self.bf self.ifstack.append(-2) else: - self.valdict["0"] = self.mem - self.mem += 1 - self.bf += ( - self.movptr(self.valdict["0"]) - + "+" - + self.movptr(self.playfield - 2) - + "[-]]" - + self.movptr(self.valdict["0"]) - + "-" - ) self.bf += ( - self.movptr(self.playfield - 1) - + "[" - + "-" - + "]" - + self.movptr(self.playfield - 2) - + "[" - + "-" - + "]" - + self.movptr(self.valdict["0"]) - + "[" - + self.movptr(self.playfield - 1) - + "+" - + self.movptr(self.playfield - 2) - + "+" - + self.movptr(self.valdict["0"]) - + "-" - + "]" - + self.movptr(self.playfield - 1) - + "[" - + self.movptr(self.valdict["0"]) - + "+" - + self.movptr(self.playfield - 1) + self.movptr(x) + "-" - + "]" - + self.movptr(self.playfield - 2) + + self.movptr(y) + + "[-]]" + + self.movptr(x) + "[" ) - self.ifstack.append(self.valdict["0"]) + self.ifstack.append(z) + self.ifvarstack.append(x) if code.startswith("outc("): if not (code.endswith(")")): raise Exception("Unmatched bracket") @@ -231,12 +279,8 @@ def program(self, code): self.bf += self.movptr(self.valdict[vn]) self.bf += "." else: - self.bf += ( - self.movptr(self.playfield - 1) - + "[-]" - + "+" * int(vn) - + ".[-]" - ) + ivn = int(vn) + self.bf += self.movptr(0) + "[-]" + getstr(ivn) + ".[-]" elif code.startswith("out("): if not (code.endswith(")")): raise Exception("Unmatched bracket") @@ -270,10 +314,11 @@ def program(self, code): + "]" ) else: + ivn = int(vn) self.bf += ( self.movptr(0) + "[-]" - + "+" * int(vn) + + getstr(ivn) + ">[-]>[-]+>[-]+<[>[-<-<<[->+>+<<]>[-<+>]>>]++++++++++>[-]+>[-]>[-]>[-]<<<<<[->-[>+>>]>[[-<+>]+>+>>]<<<<<]>>-[-<<+>>]<[-]++++++++[-<++++++>]>>[-<<+>>]<<]<[.[-]<]<[-]" ) elif code.startswith("add("): @@ -696,17 +741,179 @@ def program(self, code): raise Exception("Unmatched bracket") s = code[6:-1] tmppos = self.ptr - self.bf += self.movptr(self.playfield - 1) + self.bf += self.movptr(self.playfield - 2) for i in s: if ord(i) > 255: raise Exception("print() only supports ASCII") + else: + self.bf += getstr(ord(i)) + "." + "[-]" + self.bf += self.movptr(tmppos) + elif code.startswith("ptr("): + if not (code.endswith(")")): + raise Exception("Unmatched bracket") + a, b = code[4:-1].split(",") + if a not in self.valdict or b not in self.valdict: + raise Exception("Variable not found") + self.bf += self.movptr(self.valdict[b]) + getstr(self.valdict[a]) + elif code.startswith("bf "): + self.bf += code[4:-1] + elif code.startswith("ref("): + if not (code.endswith(")")): + raise Exception("Unmatched bracket") + a, b = code[4:-1].split(",") + if a not in self.valdict: + raise Exception("Variable not found") + if b.isdigit(): + b = int(b) + self.bf += ( + self.movptr(0) + + "[-]" + + self.movptr(b) + + "[" + + self.movptr(0) + + "+" + + self.movptr(1) + + "+" + + self.movptr(b) + + "-]" + + self.movptr(self.valdict[a]) + + "[-]" + + self.movptr(0) + + "[" + + self.movptr(self.valdict[a]) + + "+" + + self.movptr(0) + + "-" + + "]" + + self.movptr(1) + + "[" + + self.movptr(b) + + "+" + + self.movptr(1) + + "-]" + ) + else: + if b not in self.valdict: + raise Exception("Variable not found") + else: + self.bf += ( + self.movptr(self.valdict[a]) + + "[-]" + + self.movptr(self.playfield - 4) + + "[-]" + + self.movptr(self.valdict[b]) + + "[" + + self.movptr(self.playfield - 2) + + "+" + + self.movptr(self.playfield - 8) + + "+" + + self.movptr(self.valdict[b]) + + "-]" + + self.movptr(self.playfield - 5) + + "[-]++" + + self.movptr(self.playfield - 1) + + "[-]+" + + self.movptr(self.playfield - 2) + + "-" * (self.playfield - 2) + + "[" + + self.movptr(self.playfield - 1) + + "-[+>>-]>>[-]+<<--[++<<--]++>>>>" + + self.movptr(self.playfield - 2) + + "--]" + + self.movptr(self.playfield - 1) + + "-[+>>-]+<[>--[++<<--]++<+>>>>>-[+>>-]+<-]>--[++<<--]++>>>>" + + self.movptr(self.playfield - 8) + + "[" + + self.movptr(self.valdict[b]) + + "+" + + self.movptr(self.playfield - 8) + + "-]" + + self.movptr(self.playfield - 6) + + "[" + + self.movptr(self.valdict[a]) + + "+" + + self.movptr(self.playfield - 1) + + "-[+>>-]+<+>--[++<<--]++>>>>" + + self.movptr(self.playfield - 6) + + "-]" + ) + elif code.startswith("set("): + if not (code.endswith(")")): + raise Exception("Unmatched bracket") + a, b = code[4:-1].split(",") + if not a.isdigit(): + if a not in self.valdict: + raise Exception("Variable not found") else: self.bf += ( - ("+" * ord(i) if ord(i) < 128 else "-" * ord(256 - i)) - + "." + self.movptr(self.playfield - 11) + "[-]" + + self.movptr(self.playfield - 10) + + "[-]" + + self.movptr(self.valdict[a]) + + "[" + + self.movptr(self.playfield - 11) + + "+" + + self.movptr(self.playfield - 10) + + "+" + + self.movptr(self.valdict[a]) + + "-]" + + self.movptr(self.playfield - 11) + + "[" + + self.movptr(self.valdict[a]) + + "+" + + self.movptr(self.playfield - 11) + + "-]" + ) + else: + self.bf += self.movptr(self.playfield - 10) + "[-]" + getstr(int(a)) + if b.isdigit(): + b = int(b) + self.bf += ( + self.movptr(b) + + "[-]" + + self.movptr(self.playfield - 10) + + "[" + + self.movptr(b) + + "+" + + self.movptr(self.playfield - 10) + + "-]" + ) + else: + if b not in self.valdict: + raise Exception("Variable not found") + else: + self.bf += ( + self.movptr(self.playfield - 4) + + "[-]" + + self.movptr(self.valdict[b]) + + "[" + + self.movptr(self.playfield - 2) + + "+" + + self.movptr(self.playfield - 8) + + "+" + + self.movptr(self.valdict[b]) + + "-]" + + self.movptr(self.playfield - 5) + + "[-]++" + + self.movptr(self.playfield - 1) + + "[-]+" + + self.movptr(self.playfield - 2) + + "-" * (self.playfield - 2) + + "[" + + self.movptr(self.playfield - 1) + + "-[+>>-]>>[-]+<<--[++<<--]++>>>>" + + self.movptr(self.playfield - 2) + + "--]" + + self.movptr(self.playfield - 1) + + "-[+>>-]+<[-]>--[++<<--]++<<<<<[>>>>>>>>>-[+>>-]+<+>--[++<<--]++<<<<<-]>>>>>>>>>" + + self.movptr(self.playfield - 8) + + "[" + + self.movptr(self.valdict[b]) + + "+" + + self.movptr(self.playfield - 8) + + "-]" ) - self.bf += self.movptr(tmppos) def join_semantically(self, strings): res = strings[0] @@ -758,15 +965,128 @@ def opt(self, prog): out += j * i return out.rstrip("+-><") - def compile(self, prog): + def expand(self, prog, byte): + """Expand program""" + if byte not in (1, 2, 4): + raise ValueError("Byte should by 1, 2, or 4, not {}".format(byte)) + res = "" if byte != 4 else ">" + for i in prog: + if i in expanders[byte]: + res += expanders[byte][i] + else: + res += i + return res + + def getmacros(self, prog): + macros = {} + macro = [] + no_macro = [] + macro_name = "" + for i in prog.split("\n"): + i = i.strip() + if i == "endmacro": + macros[macro_name] = macro + macro_name = "" + macro = [] + continue + if macro_name: + macro.append(i) + continue + y = i + while " " in y: + y = y.replace(" ", " ") + y, k = y[: y.find(" ")], y[y.find(" ") :].replace(" ", "") + if y == "macro": + if not k.startswith("$"): + raise SyntaxError("Macros must start with '$'") + macro_name = k + else: + no_macro.append(i) + return (macros, "\n".join(no_macro)) + + def preprocess_libraries(self, prog): + flag = False + res = [] + for i in prog.split("\n"): + i = i.strip() + if i and i[0] == "?": + try: + with open(i[1:].strip(), "r") as f: + c = f.read().split("\n") + res += c + except FileNotFoundError: + try: + with open( + os.path.join( + os.path.dirname(__file__), "stdlib", i[1:].strip() + ), + "r", + ) as f: + c = f.read().split("\n") + res += c + except: + raise FileNotFoundError(f"Library {i[1:].strip()} not found") + flag = True + else: + res.append(i) + return flag, "\n".join(res) + + def can_be_preprocessed(self, prog): + macros, no_macro = self.getmacros(prog) + for i in no_macro.split("\n"): + if i.startswith("$"): + return True + return False + + def preprocess(self, macros, no_macro): + """Preprocess macros""" + res = [] + for i in no_macro.split("\n"): + i = i.split("#")[0].strip() + if i.startswith("$"): + if "(" not in i: + res += macros[i] + else: + mac_name, mac_args = i[: i.find("(")], i[i.find("(") :] + for name, info in macros.items(): + if name.startswith(mac_name + "("): + _args = name[name.find("(") :] + args1, args2 = mac_args[1:-1].split(","), _args[1:-1].split( + "," + ) + if len(args1) != len(args2): + raise SyntaxError("Argument table length wrong") + for j in info: + if j.strip().startswith("print("): + res.append(j) + else: + t = j + for _i, _j in zip(args2, args1): + t = re.sub("\\b" + re.escape(_i) + "\\b", _j, t) + res.append(t) + break + else: + res.append(i) + return "\n".join(res) + + def compile(self, prog, byte=1): """Compiles BFFuck programs into brainfuck""" clean = "" + flag, prog = self.preprocess_libraries(prog) + while flag: + flag, prog = self.preprocess_libraries(prog) + all_macros = {} + while self.can_be_preprocessed(prog): + macros, no_macro = self.getmacros(prog) + for i, j in macros.items(): + all_macros[i] = j + prog = self.preprocess(all_macros, no_macro) for i in prog.split("\n"): if len(i.strip()) == 0: continue - if i.strip().startswith("print("): - clean = i.strip() # Print needs to preserve whitespaces + if i.strip().startswith("print(") or i.strip().startswith("bf "): + clean = i.strip() # Print and bf need to preserve whitespaces else: clean = self.join_semantically(i.split()).split("#")[0] self.program(clean) - return self.opt(self.bf) + return self.opt(self.expand(self.opt(self.bf), byte)) diff --git a/examples/fib20.bff b/examples/fib20.bff new file mode 100644 index 0000000..9422ec4 --- /dev/null +++ b/examples/fib20.bff @@ -0,0 +1,15 @@ +# This example computes the first 20 terms of Fibonacci sequence, as opposed to the one in Esolang which only computes the first 14, as such, you need byte=2 or byte=4 to compile this +a=0 +b=1 +c=20 +d=0 +while(c) +sub(c,1) +add(d,a) +add(d,b) +out(a) +outc(10) +a=b +b=d +d=0 +endwhile diff --git a/examples/fizzbuzz.bff b/examples/fizzbuzz.bff new file mode 100644 index 0000000..fedd6ad --- /dev/null +++ b/examples/fizzbuzz.bff @@ -0,0 +1,31 @@ +i=1 +a=101 +b=1 +eq(a,i) +sub(b,a) +while(b) + t=i + mod(t,3) + u=i + mod(u,5) + if(t) + if(u) + out(i) + else + print(Buzz) + endif + + else + if(u) + print(Fizz) + else + print(FizzBuzz) + endif + endif + outc(10) + add(i,1) + a=101 + b=1 + eq(a,i) + sub(b,a) +endwhile diff --git a/examples/macrotest.bff b/examples/macrotest.bff new file mode 100644 index 0000000..d616387 --- /dev/null +++ b/examples/macrotest.bff @@ -0,0 +1,19 @@ +macro $c(a,b) +c=0 +add(c,a) +add(c,b) +out(c) +outc(10) +endmacro +macro $d(a,b) +print(First operand: ) +out(a) +outc(10) +print(Second operand: ) +out(b) +outc(10) +print(Sum: ) +$c(a,b) +endmacro +$d(3,7) +$d(5,6)