Compare commits

..

31 Commits

Author SHA1 Message Date
Raymon Zutekouw 2aeb187b36
Re-use memory with a free-list 3 years ago
Raymon Zutekouw 64f097b0ff
Test parse_constant 3 years ago
Raymon Zutekouw cecf68905a
CI_GH: use actions-rs 3 years ago
Raymon Zutekouw b53c7dd30d
Add GitHub CI 3 years ago
Raymon Zutekouw 0b87b957af
Cleanup main.rs by fixing warnings 3 years ago
Raymon Zutekouw f21a46b374
Complete crate info 3 years ago
Raymon Zutekouw 06b76b5d4e
Create README.md with LICENCES 3 years ago
Raymon Zutekouw b37e759485
Cleanup errors 3 years ago
Raymon Zutekouw 303da9ff9e
Remove instruction prints 3 years ago
Raymon Zutekouw aff0ed0034
Implement copy 3 years ago
Raymon Zutekouw 20869b55c1
Implement addv and subv 3 years ago
Raymon Zutekouw 5476b6d8f2
Extract pointing to mem_address to new instruction 3 years ago
Raymon Zutekouw d26500251d
Parse constants unsigned 3 years ago
Raymon Zutekouw 2d81fe1406
Remove field value from MemCell 3 years ago
Raymon Zutekouw f2934ace5d
Remove addb and subb 3 years ago
Raymon Zutekouw 82fcfea43a
Extract non-expanding instructions to `to_bf` 3 years ago
Raymon Zutekouw d04ecaeef5
Remove match on Rule::instruction 3 years ago
Raymon Zutekouw 525d3a6c70
Implement #include 3 years ago
Raymon Zutekouw bbfb030ccf
Implement loopBlock 3 years ago
Raymon Zutekouw 780523fb91
Implement print 3 years ago
Raymon Zutekouw 5650f1056d
Implement getchr 3 years ago
Raymon Zutekouw 0504985308
Implement setz 3 years ago
Raymon Zutekouw 123c1cee64
Implement basic add and sub 3 years ago
Raymon Zutekouw 0bdd6364a7
Remove field is_allocated from MemCell 3 years ago
Raymon Zutekouw b05b286d57
Implement pointm 3 years ago
Raymon Zutekouw 9a54fe353d
Implement point 3 years ago
Raymon Zutekouw 5aaa27632c
Implement delvar 3 years ago
Raymon Zutekouw 1433cf64f5
Panic on duplicate variable creation 3 years ago
Raymon Zutekouw 92d164dd78
Implement var 3 years ago
Raymon Zutekouw e1150e2280
Fill-in struct fields 3 years ago
Raymon Zutekouw e23239eb84
Pass state to instruct 3 years ago
  1. 16
      .github/workflows/ci.yml
  2. 12
      Cargo.toml
  3. 201
      LICENSE-APACHE
  4. 21
      LICENSE-MIT
  5. 32
      README.md
  6. 40
      src/grammars/mblf.pest
  7. 302
      src/main.rs

@ -0,0 +1,16 @@
name: MBLF CI
on: [push]
jobs:
build_and_format_and_test:
name: Rust project
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions-rs/toolchain@v1
with:
toolchain: stable
- run: cargo build --release
- run: cargo clippy -- -Dwarnings
- run: cargo test

@ -2,8 +2,18 @@
name = "mblf"
version = "0.1.0"
edition = "2018"
description = """
The MBLF-To-BF compiler written in Rust with Pest.
MBLF is a programming language on top of the esoteric programming language Brainfuck
"""
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
authors = ["Raymon Zutekouw <contact@raymon.dev>"]
repository = "https://github.com/MBLF-Project/mblf"
license = "MIT OR Apache-2.0"
keywords = ["compiler", "mblf", "brainfuck", "pest"]
categories = ["compilers", "command-line-utilities", "parser-implementations"]
[dependencies]
anyhow = "1.0.44"

@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2022 Raymon Zutekouw
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2022 Raymon Zutekouw
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

@ -0,0 +1,32 @@
# MBLF
<img src="https://avatars.githubusercontent.com/u/77209611?s=200&v=4" alt="MBLF-logo" width="100px" />
MBLF is a programming language on top of the esoteric programming language Brainfuck.
## Installation:
The easiest option is with cargo (rust's package manager):
`cargo install mblf`
## Usage:
If installed with cargo and it's in path:
`mblf input_mblf_file output_bf_file`
# License
Licensed under either of
- Apache License, Version 2.0
([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0)
- MIT license
([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT)
at your option.
# Contribution
Unless you explicitly state otherwise, any contribution intentionally submitted
for inclusion in the work by you, as defined in the Apache-2.0 license, shall be
dual licensed as above, without any additional terms or conditions.

@ -11,27 +11,26 @@ num =_{ hexNum | decNum }
constant = { char | num }
path = { "\"" ~ (!"\"" ~ ANY)+ ~ "\"" }
include = { "#include" ~ path }
include =@{ "#include" ~ spacing+ ~ path }
var = { "var" ~ variable }
delvar = { "delvar" ~ variable }
var =@{ "var" ~ spacing+ ~ variable }
delvar =@{ "delvar" ~ spacing+ ~ variable }
point = { "point" ~ variable }
pointm = { "pointm" ~ variable }
point =@{ "point" ~ spacing+ ~ variable }
pointa =@{ "pointa" ~ spacing+ ~ num }
pointm =@{ "pointm" ~ spacing+ ~ variable }
add = { "add" ~ constant }
addb = { "addb" ~ constant }
addv = { "addv" ~ variable }
add =@{ "add" ~ spacing+ ~ constant }
addv =@{ "addv" ~ spacing+ ~ variable }
sub = { "sub" ~ constant }
subb = { "subb" ~ constant }
subv = { "subv" ~ variable }
sub =@{ "sub" ~ spacing+ ~ constant }
subv =@{ "subv" ~ spacing+ ~ variable }
copy = { "copy" ~ variable }
setz = { "setz" }
copy =@{ "copy" ~ spacing+ ~ variable }
setz =@{ "setz" }
getchr = { "getchr" }
print = { "print" }
getchr =@{ "getchr" }
print =@{ "print" }
macaroo =_{ include }
instruction =_{ macaroo
@ -40,14 +39,13 @@ instruction =_{ macaroo
| delvar
| point
| pointa
| pointm
| add
| addb
| addv
| sub
| subb
| subv
| copy
@ -61,14 +59,16 @@ loopBlockStart = { "[" ~ NEWLINE }
loopBlockEnd = { "]" }
loopBlock = { loopBlockStart
~ statements
~ loopBlockEnd
~ spacing* ~ loopBlockEnd
}
statement =_{ (instruction | loopBlock) }
statement =_{ spacing*
~ (instruction | loopBlock)
}
statements =_{ (statement | NEWLINE)* }
WHITESPACE =_{ " " | "\t" }
spacing =_{ " " | "\t" }
COMMENT =_{ ";;" ~ (!NEWLINE ~ ANY)* ~ NEWLINE+ }
file = { SOI ~ (statement ~ NEWLINE+)* ~ EOI }

@ -1,7 +1,10 @@
#![allow(clippy::from_str_radix_10)]
use std::cmp::Ordering;
use std::collections::HashMap;
use std::fs::File;
use std::io::Write;
use anyhow::{Context, Result};
use anyhow::Result;
use string_builder::Builder;
use structopt::StructOpt;
@ -16,6 +19,23 @@ use pest::Parser;
#[grammar = "grammars/mblf.pest"]
struct MblfParser;
struct MemCell {
address: u32,
}
impl MemCell {
pub fn allocate_to(address: u32) -> Self {
Self { address }
}
}
struct State {
alloc_cnt: u32,
free_list: Vec<u32>,
mem_pointer: u32,
variables: HashMap<String, MemCell>,
}
#[derive(StructOpt)]
struct Cli {
#[structopt(parse(from_os_str))]
@ -36,137 +56,187 @@ fn extract_operand(statement: Pair<Rule>) -> &str {
line
}
fn parse_constant(text: &str) -> Result<i32, std::num::ParseIntError> {
if text.starts_with("\"") {
fn parse_constant(text: &str) -> Result<u32, std::num::ParseIntError> {
if text.starts_with('\"') {
let c = text.chars().nth(1).unwrap();
Ok(c as i32)
Ok(c as u32)
} else if text.starts_with("0x") {
let without_prefix = text.trim_start_matches("0x");
i32::from_str_radix(without_prefix, 16)
u32::from_str_radix(without_prefix, 16)
} else {
i32::from_str_radix(text, 10)
u32::from_str_radix(text, 10)
}
}
fn instruct(statement: Pair<Rule>, out: &mut Builder) {
match statement.as_rule() {
Rule::include => {
let file_path = extract_operand(statement);
println!("Including {} into this src file", file_path);
out.append("#include\n");
}
fn to_bf(rule: Rule, operand: &str, state: &mut State, out: &mut Builder) {
match rule {
Rule::var => {
let variable_name = extract_operand(statement);
println!("Creation of variable '{}'", variable_name);
out.append("var\n");
let variable_name = operand;
let mem_extension: u32;
let new_address: u32;
if !state.free_list.is_empty() {
new_address = state.free_list.pop().unwrap();
mem_extension = 0;
} else {
new_address = state.alloc_cnt;
mem_extension = 1;
}
if let Some(_v) = state.variables.insert(
String::from(variable_name),
MemCell::allocate_to(new_address),
) {
panic!("Variable '{}' already exists", variable_name);
}
state.alloc_cnt += mem_extension;
}
Rule::delvar => {
let variable_name = extract_operand(statement);
println!("Deletion of variable '{}'", variable_name);
out.append("delvar\n");
let variable_name = operand;
let memcell = state
.variables
.get(variable_name)
.ok_or_else(|| format!("Variable '{}' did not exists", variable_name))
.unwrap();
state.free_list.push(memcell.address);
state.variables.remove(&String::from(variable_name));
}
Rule::point => {
let variable_name = extract_operand(statement);
println!("Pointing to variable '{}'", variable_name);
out.append("point\n");
let variable_name = operand;
let address = state
.variables
.get(variable_name)
.unwrap_or_else(|| panic!("Variable '{}' did not exists", variable_name))
.address
.to_string();
to_bf(Rule::pointa, &address, state, out)
}
Rule::pointa => {
let address = operand;
let address_parsed = parse_constant(address).unwrap();
match address_parsed.cmp(&state.mem_pointer) {
Ordering::Less => {
out.append("<".repeat((state.mem_pointer - address_parsed) as usize))
}
Ordering::Greater => {
out.append(">".repeat((address_parsed - state.mem_pointer) as usize))
}
Ordering::Equal => (),
}
state.mem_pointer = address_parsed;
}
Rule::pointm => {
let variable_name = extract_operand(statement);
println!("Pointing back to marker variable {}", variable_name);
out.append("pointm\n");
let variable_name = operand;
let address = state
.variables
.get(variable_name)
.unwrap_or_else(|| panic!("Marker variable '{}' did not exists", variable_name))
.address;
// thank you mixtela
out.append("<+[-<+]-");
state.mem_pointer = address;
}
Rule::add => {
let constant = extract_operand(statement);
let constant_parsed = parse_constant(constant).unwrap();
println!(
"Addition of '{}', decimal value is {}",
constant, constant_parsed
);
out.append("add\n");
}
Rule::addb => {
let constant = extract_operand(statement);
let constant = operand;
let constant_parsed = parse_constant(constant).unwrap();
println!(
"Big Addition of '{}', decimal value is {}",
constant, constant_parsed
);
out.append("addb\n");
out.append("+".repeat(constant_parsed as usize));
}
Rule::addv => {
let variable_name = extract_operand(statement);
println!("Addition to variable '{}'", variable_name);
out.append("addv\n");
let variable_name = operand;
let source_address = state.mem_pointer.to_string();
out.append("[");
to_bf(Rule::sub, "1", state, out);
to_bf(Rule::point, variable_name, state, out);
to_bf(Rule::add, "1", state, out);
to_bf(Rule::pointa, &source_address, state, out);
out.append("]");
}
Rule::sub => {
let constant = extract_operand(statement);
let constant = operand;
let constant_parsed = parse_constant(constant).unwrap();
println!(
"Subtraction of '{}', decimal value is {}",
constant, constant_parsed
);
out.append("sub\n");
}
Rule::subb => {
let constant = extract_operand(statement);
let constant_parsed = parse_constant(constant).unwrap();
println!(
"Big Subtraction of '{}', decimal value is {}",
constant, constant_parsed
);
out.append("subb\n");
out.append("-".repeat(constant_parsed as usize));
}
Rule::subv => {
let variable_name = extract_operand(statement);
println!("Subtraction from variable '{}'", variable_name);
out.append("subv\n");
let variable_name = operand;
let source_address = state.mem_pointer.to_string();
out.append("[");
to_bf(Rule::sub, "1", state, out);
to_bf(Rule::point, variable_name, state, out);
to_bf(Rule::sub, "1", state, out);
to_bf(Rule::pointa, &source_address, state, out);
out.append("]");
}
Rule::copy => {
let variable_name = extract_operand(statement);
println!("Copy to variable '{}'", variable_name);
out.append("copy\n");
let variable_name = operand;
let source_address = state.mem_pointer.to_string();
to_bf(Rule::var, "__temp", state, out);
out.append("[");
to_bf(Rule::sub, "1", state, out);
to_bf(Rule::point, variable_name, state, out);
to_bf(Rule::add, "1", state, out);
to_bf(Rule::point, "__temp", state, out);
to_bf(Rule::add, "1", state, out);
to_bf(Rule::pointa, &source_address, state, out);
out.append("]");
to_bf(Rule::point, "__temp", state, out);
out.append("[");
to_bf(Rule::sub, "1", state, out);
to_bf(Rule::pointa, &source_address, state, out);
to_bf(Rule::add, "1", state, out);
to_bf(Rule::point, "__temp", state, out);
out.append("]");
to_bf(Rule::delvar, "__temp", state, out);
}
Rule::setz => {
println!("Set current variable to zero");
out.append("setz\n");
out.append("[-]");
}
Rule::getchr => {
println!("Reading char from user input into current variable");
out.append("getchr\n");
out.append(",");
}
Rule::print => {
println!("Printing current variable");
out.append("print\n");
}
Rule::instruction => {
out.append("\n");
}
Rule::loopBlock => {
for nested_statement in statement.into_inner() {
instruct(nested_statement, out);
}
out.append(".");
}
Rule::loopBlockStart => {
println!("Start of loopBlock");
out.append("loopBlockStart\n");
out.append("[");
}
Rule::loopBlockEnd => {
println!("End of loopBlock");
out.append("loopBlockEnd\n");
out.append("]");
}
Rule::EOI => {
println!("End of Input");
out.append("\n");
}
_ => unreachable!(),
}
}
fn instruct(statement: Pair<Rule>, state: &mut State, out: &mut Builder) {
match statement.as_rule() {
Rule::include => {
let file_path_raw = extract_operand(statement);
let file_path = &file_path_raw[1..file_path_raw.len() - 1];
let content = std::fs::read_to_string(&file_path).unwrap();
let parsed_file = MblfParser::parse(Rule::file, &content)
.expect("Parse Error")
.next()
.unwrap();
for statement in parsed_file.into_inner() {
instruct(statement, state, out);
}
}
Rule::loopBlock => {
for nested_statement in statement.into_inner() {
instruct(nested_statement, state, out);
}
}
_ => to_bf(statement.as_rule(), extract_operand(statement), state, out),
}
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let args = Cli::from_args();
let content = std::fs::read_to_string(&args.input_file)
.with_context(|| format!("could not read source file {:?}", args.input_file))?;
let content = std::fs::read_to_string(&args.input_file)?;
let mut builder = Builder::default();
@ -175,15 +245,71 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
.next()
.unwrap();
for statement in parsed_file.into_inner() {
instruct(statement, &mut builder);
let mut state = State {
alloc_cnt: 0,
free_list: Vec::new(),
mem_pointer: 0,
variables: HashMap::new(),
};
for stmt in parsed_file.into_inner() {
instruct(stmt, &mut state, &mut builder);
}
let bf = builder.string().unwrap();
let mut out = File::create(args.output_file)?;
out.write(bf.as_bytes())?;
out.write_all(bf.as_bytes())?;
out.sync_all()?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_parse_constant() {
assert_eq!(parse_constant(&"42"), Ok(42));
assert_eq!(parse_constant(&"0x2A"), Ok(42));
assert_eq!(parse_constant(&"\"*\""), Ok(42));
assert!(
matches!(
parse_constant(&"\'*\'"),
Err(std::num::ParseIntError { .. })
),
"Char literals are declared with \"_\", not \'_\'"
);
}
#[test]
fn test_reuse_of_free_memcells() {
let mut builder = Builder::default();
let mut state = State {
alloc_cnt: 0,
free_list: Vec::new(),
mem_pointer: 0,
variables: HashMap::new(),
};
to_bf(Rule::var, "abc", &mut state, &mut builder);
assert_eq!(state.alloc_cnt, 1);
to_bf(Rule::delvar, "abc", &mut state, &mut builder);
assert_eq!(
state.alloc_cnt, 1,
"allocation should not be shrunken, that is too costly"
);
to_bf(Rule::var, "def", &mut state, &mut builder);
assert_ne!(
state.alloc_cnt, 2,
"the just de-allocated memorycell should be re-used"
);
assert_eq!(
state.alloc_cnt, 1,
"alloc, dealloc, alloc has a max usage of one memorycell"
);
}
}

Loading…
Cancel
Save