├── .gitignore ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── COPYRIGHT.md ├── LICENSE-APACHE.md ├── LICENSE-MIT.md ├── README.md ├── libruse-eval ├── Cargo.toml └── src │ └── lib.rs ├── libruse-print ├── Cargo.toml └── src │ └── lib.rs ├── libruse-read ├── Cargo.toml └── src │ ├── error.rs │ ├── lex │ ├── error.rs │ ├── mod.rs │ ├── token.rs │ └── token_iterator.rs │ ├── lib.rs │ └── parse │ ├── error.rs │ ├── expr.rs │ └── mod.rs ├── libruse ├── Cargo.toml └── src │ ├── error.rs │ └── lib.rs └── ruse ├── Cargo.toml └── src └── main.rs /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled files 2 | *.o 3 | *.so 4 | *.rlib 5 | *.dll 6 | 7 | # Executables 8 | *.exe 9 | 10 | # Generated by Cargo 11 | target 12 | 13 | # Remove Cargo.lock from gitignore if creating an executable, leave it for libraries 14 | # More information here http://doc.crates.io/guide.html#cargotoml-vs-cargolock 15 | Cargo.lock 16 | 17 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. 6 | 7 | ## Our Standards 8 | 9 | Examples of behavior that contributes to creating a positive environment include: 10 | 11 | * Using welcoming and inclusive language 12 | * Being respectful of differing viewpoints and experiences 13 | * Gracefully accepting constructive criticism 14 | * Focusing on what is best for the community 15 | * Showing empathy towards other community members 16 | 17 | Examples of unacceptable behavior by participants include: 18 | 19 | * The use of sexualized language or imagery and unwelcome sexual attention or advances 20 | * Trolling, insulting/derogatory comments, and personal or political attacks 21 | * Public or private harassment 22 | * Publishing others' private information, such as a physical or electronic address, without explicit permission 23 | * Other conduct which could reasonably be considered inappropriate in a professional setting 24 | 25 | ## Our Responsibilities 26 | 27 | Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. 28 | 29 | Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. 30 | 31 | ## Scope 32 | 33 | This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. 34 | 35 | ## Enforcement 36 | 37 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at me@andrewbrinker.com. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. 38 | 39 | Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. 40 | 41 | ## Attribution 42 | 43 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] 44 | 45 | [homepage]: http://contributor-covenant.org 46 | [version]: http://contributor-covenant.org/version/1/4/ 47 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | Hey! First of all, thanks for contributing or thinking or contributing to Ruse! 2 | 3 | Ruse's contributing process is pretty lightweight. If you have a question or idea about Ruse, 4 | open an issue. If you want to contribute, open a pull request. Pull requests are squashed into 5 | one commit before merging, to keep the history reasonably easy to follow. We're happy to work 6 | with you to get your pull request into the state it needs to be. For now, we only care that 7 | you've: 8 | 9 | - Run [`rustfmt`](https://github.com/rust-lang-nursery/rustfmt) over your changes 10 | - Run [Clippy](https://github.com/Manishearth/rust-clippy) over your changes 11 | 12 | If you have any questions, don't hesitate to ask! 13 | -------------------------------------------------------------------------------- /COPYRIGHT.md: -------------------------------------------------------------------------------- 1 | The Ruse Project is dual-licensed under the terms of 2 | the Apache 2.0 and MIT licenses. The full terms of these 3 | licenses can be found in the `LICENSE-APACHE.md` and 4 | `LICENSE-MIT.md` files. 5 | 6 | The contents of the files `README.md`, `CODE_OF_CONDUCT.md`, 7 | `CONTRIBUTING.md`, `COPYRIGHT.md` (this file), `LICENSE-APACHE.md`, 8 | `LICENSE-MIT.md`, as well as any example code in this project, are 9 | licensed under the Creative Commons Attribution 4.0 International 10 | license (CC BY 4.0), the full text of which may be found at 11 | [https://creativecommons.org/licenses/by/4.0/][cc]. 12 | 13 | [cc]: https://creativecommons.org/licenses/by/4.0/ 14 | 15 | -------------------------------------------------------------------------------- /LICENSE-APACHE.md: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2017 Ruse Language Developers 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /LICENSE-MIT.md: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2017 Ruse Language Developers 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | 23 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Ruse 2 | 3 | This is an experimental project to create an R7RS small-specification-compliant 4 | Scheme as an embedded language in Rust, similar to the relationship between Lua 5 | and C. 6 | 7 | ## Specification 8 | 9 | The goal is for Ruse to be compliant with the R7RS small specification, along 10 | with whatever additional features are deemed necessary or desirable. 11 | 12 | The specification may be found here: http://www.scheme-reports.org/ 13 | 14 | The 7th edition of the Scheme standard was chosen for several reasons. First, 15 | that it is the most recent edition of the standard. Second, that it retains 16 | the smallness and simplicity of R5RS, which many felt was lost in the 17 | language's 6th version. Finally, the most recent Scheme report is the easiest 18 | to find. 19 | 20 | It is likely that additional features will be implemented that are not 21 | described in the R7RS small specification. This is fine, and should be no 22 | cause for concern so long as the specified semantics are maintained. 23 | 24 | ## Project Goals 25 | 26 | The main goal of Ruse is to be a learning project and learning experience for 27 | those who make and use it. It may be that it becomes a more serious effort at 28 | some point in the future, but for now it is little more than a hobbyist's 29 | project. It allows the contributors to experiment and stretch themselves a bit 30 | with implementing a programming language, without the pressure of concern that 31 | anyone will actually use it. That said, if you do use it, let us know how it 32 | goes. 33 | 34 | ## Contributing 35 | 36 | See the [CONTRIBUTING.md](CONTRIBUTING.md) file. 37 | 38 | ## Structure 39 | 40 | Ruse is structured currently into 5 separate Rust crates. 41 | 42 | - `ruse` is the Ruse interpreter, and is a binary. 43 | - `libruse` is the library interface to Ruse. The CLI just uses `libruse`. 44 | - `libruse-read` is the reading portion of the interpreter. 45 | - `libruse-eval` is the evaluation portion of the interpreter. 46 | - `libruse-print` is the printing portion of the interpreter. 47 | 48 | -------------------------------------------------------------------------------- /libruse-eval/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "libruse-eval" 3 | version = "0.1.0" 4 | authors = ["Andrew Brinker "] 5 | 6 | [dependencies] 7 | libruse-read = { path = "../libruse-read" } 8 | -------------------------------------------------------------------------------- /libruse-eval/src/lib.rs: -------------------------------------------------------------------------------- 1 | //! Evaluates Ruse expressions 2 | 3 | #![deny(missing_docs)] 4 | 5 | extern crate libruse_read as read; 6 | 7 | use read::parse::expr::Expr; 8 | 9 | // TODO: Implement this function. 10 | /// Evaluates an expression into a result for printing. 11 | pub fn eval(_: Expr) -> Result { 12 | unimplemented!() 13 | } 14 | -------------------------------------------------------------------------------- /libruse-print/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "libruse-print" 3 | version = "0.1.0" 4 | authors = ["Andrew Brinker "] 5 | 6 | [dependencies] 7 | libruse-read = { path = "../libruse-read" } 8 | -------------------------------------------------------------------------------- /libruse-print/src/lib.rs: -------------------------------------------------------------------------------- 1 | //! Prints the result of evaluation. 2 | 3 | #![deny(missing_docs)] 4 | 5 | extern crate libruse_read as read; 6 | 7 | use read::parse::expr::Expr; 8 | 9 | // TODO: Implement this function. 10 | /// Print a Ruse expression. 11 | pub fn print(_: Expr) -> Result { 12 | unimplemented!() 13 | } 14 | -------------------------------------------------------------------------------- /libruse-read/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "libruse-read" 3 | version = "0.1.0" 4 | authors = ["Andrew Brinker "] 5 | 6 | [dependencies] 7 | -------------------------------------------------------------------------------- /libruse-read/src/error.rs: -------------------------------------------------------------------------------- 1 | use lex; 2 | use parse; 3 | use parse::expr::Expr; 4 | use std::error; 5 | use std::fmt; 6 | use std::result; 7 | 8 | pub type Result = result::Result; 9 | 10 | #[derive(Debug, PartialEq)] 11 | pub enum Error { 12 | LexError(lex::Error), 13 | ParseError(parse::Response), 14 | } 15 | 16 | impl error::Error for Error { 17 | fn description(&self) -> &str { 18 | match *self { 19 | Error::LexError(..) => "an error occured during lexing", 20 | Error::ParseError(..) => "an error occured during parsing", 21 | } 22 | } 23 | 24 | fn cause(&self) -> Option<&error::Error> { 25 | match *self { 26 | Error::LexError(ref error) => Some(error), 27 | Error::ParseError(ref error) => Some(error), 28 | } 29 | } 30 | } 31 | 32 | impl fmt::Display for Error { 33 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 34 | match *self { 35 | Error::LexError(ref error) => write!(f, "{}", error), 36 | Error::ParseError(ref error) => write!(f, "{}", error), 37 | } 38 | } 39 | } 40 | 41 | impl From for Error { 42 | fn from(err: lex::Error) -> Error { 43 | Error::LexError(err) 44 | } 45 | } 46 | 47 | impl From for Error { 48 | fn from(err: parse::Response) -> Error { 49 | Error::ParseError(err) 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /libruse-read/src/lex/error.rs: -------------------------------------------------------------------------------- 1 | use lex::token::{Token, Location}; 2 | use std::error; 3 | use std::fmt; 4 | use std::result; 5 | 6 | pub type Result = result::Result, Error>; 7 | 8 | #[derive(Debug, PartialEq)] 9 | pub enum Error { 10 | InvalidCharacter(char, Location), 11 | MalformedNumber(String, Location), 12 | InvalidLiteral(String, Location), 13 | InvalidEscapeSequence(String, Location), 14 | } 15 | 16 | impl error::Error for Error { 17 | fn description(&self) -> &str { 18 | match *self { 19 | Error::InvalidCharacter(..) => "invalid character", 20 | Error::MalformedNumber(..) => "malformed number", 21 | Error::InvalidLiteral(..) => "invalid literal", 22 | Error::InvalidEscapeSequence(..) => "invalid escape sequence", 23 | } 24 | } 25 | } 26 | 27 | impl fmt::Display for Error { 28 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 29 | match *self { 30 | Error::InvalidCharacter(character, location) => { 31 | write!( 32 | f, 33 | "invalid character '{}' at {}", 34 | character, 35 | location 36 | ) 37 | } 38 | Error::MalformedNumber(ref number, location) => { 39 | write!(f, "malformed number '{}' at '{}'", number, location) 40 | } 41 | Error::InvalidLiteral(ref string, location) => { 42 | write!(f, "invalid literal '{}' at '{}'", string, location) 43 | } 44 | Error::InvalidEscapeSequence(ref string, location) => { 45 | write!( 46 | f, 47 | "invalid escape sequence '{}' at '{}'", 48 | string, 49 | location 50 | ) 51 | } 52 | } 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /libruse-read/src/lex/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod error; 2 | pub mod token; 3 | pub mod token_iterator; 4 | pub use lex::error::{Error, Result}; 5 | use lex::token_iterator::StrTokenIterator; 6 | 7 | pub fn lex>(s: S) -> Result { 8 | // Note that the `collect` call does some magic thanks to 9 | // a stdlib impl for `Vec`. It actually auto-converts a 10 | // `Vec>` into `Result, Error>`. 11 | // This means that only the first error is retained, which 12 | // for now is what we want to do. In the future we'd likely 13 | // want to have a better strategy which doesn't halt lexing 14 | // at every error, and instead differentiates between errors 15 | // which can be worked around and errors which can't, or at 16 | // least tries to provide more information for the user to 17 | // address at once, rather than requiring a slower feedback 18 | // cycle, which can be annoying. 19 | s.as_ref().tokens().collect::() 20 | } 21 | 22 | #[cfg(test)] 23 | mod tests { 24 | use lex::lex; 25 | use lex::Error; 26 | use lex::token::{Token, Location}; 27 | 28 | #[test] 29 | fn lex_the_empty_program() { 30 | let tokens = lex(""); 31 | let expected = Ok(vec![]); 32 | assert_eq!(tokens, expected); 33 | } 34 | 35 | #[test] 36 | fn lex_a_single_open_paren() { 37 | let tokens = lex("("); 38 | let expected = 39 | Ok( 40 | vec![ 41 | Token::open_paren( 42 | Location::new(1, 1), 43 | Location::new(1, 2) 44 | ) 45 | ] 46 | ); 47 | assert_eq!(tokens, expected); 48 | } 49 | 50 | #[test] 51 | fn lex_a_single_close_paren() { 52 | let tokens = lex(")"); 53 | let expected = 54 | Ok( 55 | vec![ 56 | Token::close_paren( 57 | Location::new(1, 1), 58 | Location::new(1, 2) 59 | ) 60 | ] 61 | ); 62 | assert_eq!(tokens, expected); 63 | } 64 | 65 | #[test] 66 | fn lex_matching_parens() { 67 | let tokens = lex("()"); 68 | let expected = Ok(vec![ 69 | Token::open_paren(Location::new(1, 1), Location::new(1, 2)), 70 | Token::close_paren(Location::new(1, 2), Location::new(1, 3)), 71 | ]); 72 | assert_eq!(tokens, expected); 73 | } 74 | 75 | #[test] 76 | fn lex_a_simple_program() { 77 | let tokens = lex("(+ 2 3)"); 78 | let expected = Ok(vec![ 79 | Token::open_paren(Location::new(1, 1), Location::new(1, 2)), 80 | Token::symbol("+", Location::new(1, 2)), 81 | Token::integer(2, Location::new(1, 4), Location::new(1, 5)), 82 | Token::integer(3, Location::new(1, 6), Location::new(1, 7)), 83 | Token::close_paren(Location::new(1, 7), Location::new(1, 8)), 84 | ]); 85 | assert_eq!(tokens, expected); 86 | } 87 | 88 | #[test] 89 | fn lex_a_more_complex_program() { 90 | let tokens = lex("(+ (add-two 2) 3.2)"); 91 | let expected = Ok(vec![ 92 | Token::open_paren(Location::new(1, 1), Location::new(1, 2)), 93 | Token::symbol("+", Location::new(1, 2)), 94 | Token::open_paren(Location::new(1, 4), Location::new(1, 5)), 95 | Token::symbol("add-two", Location::new(1, 5)), 96 | Token::integer(2, Location::new(1, 13), Location::new(1, 14)), 97 | Token::close_paren(Location::new(1, 14), Location::new(1, 15)), 98 | Token::float(3.2, Location::new(1, 16), Location::new(1, 19)), 99 | Token::close_paren(Location::new(1, 19), Location::new(1, 20)), 100 | ]); 101 | assert_eq!(tokens, expected); 102 | } 103 | 104 | #[test] 105 | fn lex_a_complex_symbol() { 106 | let tokens = lex("(%a+/d 2 4)"); 107 | let expected = Ok(vec![ 108 | Token::open_paren(Location::new(1, 1), Location::new(1, 2)), 109 | Token::symbol("%a+/d", Location::new(1, 2)), 110 | Token::integer(2, Location::new(1, 8), Location::new(1, 9)), 111 | Token::integer(4, Location::new(1, 10), Location::new(1, 11)), 112 | Token::close_paren(Location::new(1, 11), Location::new(1, 12)), 113 | ]); 114 | assert_eq!(tokens, expected); 115 | } 116 | 117 | #[test] 118 | fn fail_to_lex_a_non_ascii_character() { 119 | let result = lex("(+ (¢ 3) 4)"); 120 | let expected = Err(Error::InvalidCharacter('¢', Location::new(1, 5))); 121 | assert_eq!(result, expected); 122 | } 123 | 124 | #[test] 125 | fn lex_a_short_boolean() { 126 | let result = lex("(#t)"); 127 | let expected = Ok(vec![ 128 | Token::open_paren(Location::new(1, 1), Location::new(1, 2)), 129 | Token::boolean(true, Location::new(1, 2), Location::new(1, 4)), 130 | Token::close_paren(Location::new(1, 4), Location::new(1, 5)), 131 | ]); 132 | assert_eq!(result, expected); 133 | } 134 | 135 | #[test] 136 | fn lex_a_long_boolean() { 137 | let result = lex("(#false)"); 138 | let expected = Ok(vec![ 139 | Token::open_paren(Location::new(1, 1), Location::new(1, 2)), 140 | Token::boolean(false, Location::new(1, 2), Location::new(1, 8)), 141 | Token::close_paren(Location::new(1, 8), Location::new(1, 9)), 142 | ]); 143 | assert_eq!(result, expected); 144 | } 145 | 146 | #[test] 147 | fn lex_an_invalid_literal() { 148 | let result = lex("(#what)"); 149 | let expected = Err(Error::InvalidLiteral("#what".to_string(), Location::new(1, 2))); 150 | assert_eq!(result, expected); 151 | } 152 | 153 | #[test] 154 | fn lex_a_string() { 155 | let result = lex("\"hello\""); 156 | let expected = 157 | Ok( 158 | vec![ 159 | Token::string( 160 | "hello".to_string(), 161 | Location::new(1, 1) 162 | ) 163 | ] 164 | ); 165 | assert_eq!(result, expected); 166 | } 167 | 168 | #[test] 169 | fn lex_a_string_in_a_function() { 170 | let result = lex("(f 2 \"blah\")"); 171 | let expected = Ok(vec![ 172 | Token::open_paren(Location::new(1, 1), Location::new(1, 2)), 173 | Token::symbol("f", Location::new(1, 2)), 174 | Token::integer(2, Location::new(1, 4), Location::new(1, 5)), 175 | Token::string("blah", Location::new(1, 6)), 176 | Token::close_paren(Location::new(1, 12), Location::new(1, 13)), 177 | ]); 178 | assert_eq!(result, expected); 179 | } 180 | 181 | #[test] 182 | fn lex_a_string_with_an_escape_equence() { 183 | let result = lex("(g \"hello\n\" 4)"); 184 | let expected = Ok(vec![ 185 | Token::open_paren(Location::new(1, 1), Location::new(1, 2)), 186 | Token::symbol("g", Location::new(1, 2)), 187 | Token::string("hello\n", Location::new(1, 4)), 188 | Token::integer(4, Location::new(1, 13), Location::new(1, 14)), 189 | Token::close_paren(Location::new(1, 14), Location::new(1, 15)), 190 | ]); 191 | assert_eq!(result, expected); 192 | } 193 | 194 | #[test] 195 | fn lex_mix_of_delimiters() { 196 | let result = lex("([{}])"); 197 | let expected = Ok(vec![ 198 | Token::open_paren(Location::new(1, 1), Location::new(1, 2)), 199 | Token::open_bracket(Location::new(1, 2), Location::new(1, 3)), 200 | Token::open_brace(Location::new(1, 3), Location::new(1, 4)), 201 | Token::close_brace(Location::new(1, 4), Location::new(1, 5)), 202 | Token::close_bracket(Location::new(1, 5), Location::new(1, 6)), 203 | Token::close_paren(Location::new(1, 6), Location::new(1, 7)), 204 | ]); 205 | assert_eq!(result, expected); 206 | } 207 | 208 | #[test] 209 | fn lex_multiline_program() { 210 | let program = "(+ 1 2) 211 | (+ 3 4)"; 212 | let result = lex(program); 213 | let expected = Ok(vec![ 214 | Token::open_paren(Location::new(1, 1), Location::new(1, 2)), 215 | Token::symbol("+", Location::new(1, 2)), 216 | Token::integer(1, Location::new(1, 4), Location::new(1, 5)), 217 | Token::integer(2, Location::new(1, 6), Location::new(1, 7)), 218 | Token::close_paren(Location::new(1, 7), Location::new(1,8)), 219 | 220 | Token::open_paren(Location::new(2, 1), Location::new(2, 2)), 221 | Token::symbol("+", Location::new(2, 2)), 222 | Token::integer(3, Location::new(2, 4), Location::new(2, 5)), 223 | Token::integer(4, Location::new(2, 6), Location::new(2, 7)), 224 | Token::close_paren(Location::new(2, 7), Location::new(2, 8)) 225 | ]); 226 | assert_eq!(result, expected); 227 | } 228 | 229 | #[test] 230 | fn lex_indented_multiline_program() { 231 | let program = "(+ 1 2) 232 | (+ 3 4)"; 233 | let result = lex(program); 234 | let expected = Ok(vec![ 235 | Token::open_paren(Location::new(1, 1), Location::new(1, 2)), 236 | Token::symbol("+", Location::new(1, 2)), 237 | Token::integer(1, Location::new(1, 4), Location::new(1, 5)), 238 | Token::integer(2, Location::new(1, 6), Location::new(1, 7)), 239 | Token::close_paren(Location::new(1, 7), Location::new(1,8)), 240 | 241 | Token::open_paren(Location::new(2, 24), Location::new(2, 25)), 242 | Token::symbol("+", Location::new(2, 25)), 243 | Token::integer(3, Location::new(2, 27), Location::new(2, 28)), 244 | Token::integer(4, Location::new(2, 29), Location::new(2, 30)), 245 | Token::close_paren(Location::new(2, 30), Location::new(2, 31)) 246 | ]); 247 | assert_eq!(result, expected); 248 | } 249 | } 250 | 251 | -------------------------------------------------------------------------------- /libruse-read/src/lex/token.rs: -------------------------------------------------------------------------------- 1 | use std::fmt; 2 | use std::convert::Into; 3 | 4 | #[derive(PartialEq, Clone)] 5 | pub enum TokenKind { 6 | OpenDelim(Delim), 7 | CloseDelim(Delim), 8 | Symbol(String), 9 | Integer(i64), 10 | Float(f64), 11 | Str(String), 12 | Bool(bool), 13 | // TODO: Implement line comments 14 | LineComment(String), 15 | // TODO: Implement block comments 16 | BlockComment(String), 17 | // TODO: Implement datum comments 18 | DatumComment(String), 19 | } 20 | 21 | impl fmt::Debug for TokenKind { 22 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 23 | match self { 24 | TokenKind::OpenDelim(d) => { 25 | match d { 26 | Delim::Paren => write!(f, "'('"), 27 | Delim::Bracket => write!(f, "'['"), 28 | Delim::Brace => write!(f, "'{{'"), 29 | } 30 | } 31 | TokenKind::CloseDelim(d) => { 32 | match d { 33 | Delim::Paren => write!(f, "')'"), 34 | Delim::Bracket => write!(f, "']'"), 35 | Delim::Brace => write!(f, "'}}'"), 36 | } 37 | } 38 | TokenKind::Symbol(s) => { 39 | write!(f, "'{}'", s.clone()) 40 | } 41 | TokenKind::Integer(i) => { 42 | write!(f, "'{}'", *i) 43 | } 44 | TokenKind::Float(fl) => { 45 | write!(f, "'{}'", fl) 46 | } 47 | TokenKind::Str(s) => { 48 | write!(f, "\"{}\"", s.clone()) 49 | } 50 | TokenKind::Bool(b) => { 51 | if *b { 52 | write!(f, "#t") 53 | } else { 54 | write!(f, "#f") 55 | } 56 | } 57 | TokenKind::LineComment(..) | 58 | TokenKind::BlockComment(..) | 59 | TokenKind::DatumComment(..) => write!(f, "") 60 | } 61 | } 62 | } 63 | 64 | impl TokenKind { 65 | pub fn is_open_delim(&self) -> bool { 66 | match *self { 67 | TokenKind::OpenDelim(..) => true, 68 | _ => false, 69 | } 70 | } 71 | } 72 | 73 | #[derive(PartialEq, Eq, Debug, Clone)] 74 | pub enum Delim { 75 | Paren, 76 | Bracket, 77 | Brace, 78 | } 79 | 80 | #[derive(PartialEq, Clone, Copy)] 81 | pub struct Location { 82 | pub line: usize, 83 | pub column: usize, 84 | } 85 | 86 | impl Location { 87 | pub fn new(line: usize, column: usize) -> Location { 88 | Location { line, column } 89 | } 90 | 91 | pub fn next_column(&mut self) { 92 | self.column += 1; 93 | } 94 | 95 | pub fn next_line(&mut self) { 96 | self.line += 1; 97 | self.column = 1; 98 | } 99 | } 100 | 101 | impl Default for Location { 102 | fn default() -> Location { 103 | Location { 104 | line: 1, 105 | column: 1, 106 | } 107 | } 108 | } 109 | 110 | impl fmt::Debug for Location { 111 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 112 | write!(f, "{}:{}", self.line, self.column) 113 | } 114 | } 115 | 116 | impl fmt::Display for Location { 117 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 118 | write!(f, "line {}, column {}", self.line, self.column) 119 | } 120 | } 121 | 122 | #[derive(PartialEq)] 123 | pub struct Token { 124 | pub kind: TokenKind, 125 | pub start_location: Location, 126 | pub end_location: Location, 127 | } 128 | 129 | impl fmt::Debug for Token { 130 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 131 | write!(f, "", self.kind, self.start_location, self.end_location) 132 | } 133 | } 134 | 135 | macro_rules! delim_token { 136 | ( $fn_name:ident, $kind:expr ) => { 137 | pub fn $fn_name(start_location: Location, end_location: Location) -> Token { 138 | Token { 139 | kind: $kind, 140 | start_location: start_location, 141 | end_location: end_location, 142 | } 143 | } 144 | }; 145 | } 146 | 147 | macro_rules! stringy_token { 148 | ( $fn_name:ident, $variant_name:ident ) => { 149 | pub fn $fn_name>(s: S, start_location: Location) -> Token { 150 | let s: String = s.into(); 151 | 152 | let end_location = Location { 153 | column: start_location.column + s.len(), 154 | line: start_location.line, 155 | }; 156 | 157 | Token { 158 | kind: TokenKind::$variant_name(s), 159 | start_location: start_location, 160 | end_location: end_location, 161 | } 162 | } 163 | }; 164 | } 165 | 166 | macro_rules! literal_token { 167 | ( $fn_name:ident, $variant_name:ident, $value_type:ty ) => { 168 | pub fn $fn_name(value: $value_type, 169 | start_location: Location, 170 | end_location: Location) -> Token { 171 | Token { 172 | kind: TokenKind::$variant_name(value), 173 | start_location: start_location, 174 | end_location: end_location, 175 | } 176 | } 177 | }; 178 | } 179 | 180 | impl Token { 181 | delim_token!(open_paren, TokenKind::OpenDelim(Delim::Paren)); 182 | delim_token!(close_paren, TokenKind::CloseDelim(Delim::Paren)); 183 | delim_token!(open_bracket, TokenKind::OpenDelim(Delim::Bracket)); 184 | delim_token!(close_bracket, TokenKind::CloseDelim(Delim::Bracket)); 185 | delim_token!(open_brace, TokenKind::OpenDelim(Delim::Brace)); 186 | delim_token!(close_brace, TokenKind::CloseDelim(Delim::Brace)); 187 | 188 | stringy_token!(symbol, Symbol); 189 | stringy_token!(string, Str); 190 | 191 | literal_token!(integer, Integer, i64); 192 | literal_token!(float, Float, f64); 193 | literal_token!(boolean, Bool, bool); 194 | } 195 | 196 | -------------------------------------------------------------------------------- /libruse-read/src/lex/token_iterator.rs: -------------------------------------------------------------------------------- 1 | use lex::error::Error; 2 | use lex::token::{Token, Location}; 3 | use std::cell::Cell; 4 | use std::iter::Peekable; 5 | use std::str::Chars; 6 | use std::iter::Iterator; 7 | use std::convert::Into; 8 | 9 | pub struct TokenIterator<'a> { 10 | char_iter: Peekable>, 11 | location: Cell, 12 | pub string_context: bool, 13 | } 14 | 15 | #[derive(Debug, PartialEq, Eq)] 16 | enum EndOfLine { Yes, No } 17 | 18 | impl Into for EndOfLine { 19 | fn into(self) -> bool { 20 | match self { 21 | EndOfLine::Yes => true, 22 | EndOfLine::No => false, 23 | } 24 | } 25 | } 26 | 27 | #[derive(Debug, PartialEq, Eq)] 28 | enum Move { Yes, No } 29 | 30 | impl Into for Move { 31 | fn into(self) -> bool { 32 | match self { 33 | Move::Yes => true, 34 | Move::No => false, 35 | } 36 | } 37 | } 38 | 39 | impl<'a> TokenIterator<'a> { 40 | pub fn new(s: &str) -> TokenIterator { 41 | TokenIterator { 42 | char_iter: s.chars().peekable(), 43 | location: Cell::new(Location::default()), 44 | string_context: false, 45 | } 46 | } 47 | 48 | fn get_location(&self) -> Location { 49 | self.location.get() 50 | } 51 | 52 | fn set_location(&mut self, location: Location) { 53 | self.location.set(location); 54 | } 55 | 56 | fn step(&mut self, end_of_line: EndOfLine, m: Move) { 57 | let mut location = self.get_location(); 58 | 59 | if end_of_line.into() && !self.string_context { 60 | location.next_line(); 61 | } else { 62 | location.next_column(); 63 | } 64 | 65 | self.set_location(location); 66 | 67 | if m.into() { 68 | self.char_iter.next(); 69 | } 70 | } 71 | } 72 | 73 | impl<'a> Iterator for TokenIterator<'a> { 74 | type Item = Result; 75 | 76 | /// Returns one of three things: 77 | /// 78 | /// 1. `Option::None` 79 | /// 2. `Option::Some(Result::Err(Error))` 80 | /// 3. `Option::Some(Result::Ok(Token))` 81 | /// 82 | /// Option (1) indicates that there's nothing left to parse. Option (2) 83 | /// indicates an error in the input stream. Option (3) is how the parsed 84 | /// tokens are returned to the user. 85 | fn next(&mut self) -> Option { 86 | while let Some(character) = self.char_iter.next() { 87 | 88 | // Decide what to attempt to lex based on the first character. Note that the 89 | // allowable characters for symbols are fewer here then they are in the 90 | // lex_symbol function. 91 | match character { 92 | '(' => return Some(lex_open_paren(self)), 93 | ')' => return Some(lex_closed_paren(self)), 94 | '[' => return Some(lex_open_bracket(self)), 95 | ']' => return Some(lex_closed_bracket(self)), 96 | '{' => return Some(lex_open_brace(self)), 97 | '}' => return Some(lex_closed_brace(self)), 98 | '#' => return Some(lex_boolean(self, character)), 99 | '0'...'9' => return Some(lex_number(self, character)), 100 | 'a'...'z' | 'A'...'Z' | '!' | '$' | '%' | '&' | '*' | '/' | ':' | '<' | '=' | 101 | '>' | '?' | '^' | '_' | '~' | '+' | '-' => return Some(lex_symbol(self, character)), 102 | '"' => return Some(lex_string(self, character)), 103 | // Skip whitespace. 104 | ' ' | '\t' | '\r' => self.step(EndOfLine::No, Move::No), 105 | // Count newlines 106 | '\n' => self.step(EndOfLine::Yes, Move::No), 107 | _ => return Some(Err(Error::InvalidCharacter(character, self.get_location()))), 108 | } 109 | } 110 | 111 | None 112 | } 113 | } 114 | 115 | pub trait StrTokenIterator: AsRef { 116 | fn tokens(&self) -> TokenIterator { 117 | TokenIterator::new(self.as_ref()) 118 | } 119 | } 120 | 121 | // Implement StrIterExt for all types that can be ref'ed into string slices. 122 | impl> StrTokenIterator for T {} 123 | 124 | macro_rules! lex_delim { 125 | ($name:ident, $e:ident, $span:expr) => { 126 | fn $name(iter: &mut TokenIterator) -> Result { 127 | let start_location = iter.get_location(); 128 | let end_location = Location { 129 | column: start_location.column + $span, 130 | line: start_location.line, 131 | }; 132 | 133 | iter.step(EndOfLine::No, Move::No); 134 | Ok(Token::$e(start_location, end_location)) 135 | } 136 | } 137 | } 138 | 139 | lex_delim!(lex_open_paren, open_paren, 1); 140 | lex_delim!(lex_closed_paren, close_paren, 1); 141 | lex_delim!(lex_open_bracket, open_bracket, 1); 142 | lex_delim!(lex_closed_bracket, close_bracket, 1); 143 | lex_delim!(lex_open_brace, open_brace, 1); 144 | lex_delim!(lex_closed_brace, close_brace, 1); 145 | 146 | fn lex_number(iter: &mut TokenIterator, character: char) -> Result { 147 | let mut result = vec![character]; 148 | let start = iter.get_location(); 149 | 150 | while let Some(&next_character) = iter.char_iter.peek() { 151 | match next_character { 152 | '0'...'9' | '.' => { 153 | iter.step(EndOfLine::No, Move::Yes); 154 | result.push(next_character); 155 | } 156 | _ => break, 157 | } 158 | } 159 | 160 | iter.step(EndOfLine::No, Move::No); 161 | 162 | let out: String = result.iter().cloned().collect(); 163 | let end = iter.get_location(); 164 | 165 | if let Ok(val) = out.parse::() { 166 | Ok(Token::integer(val, start, end)) 167 | } else if let Ok(val) = out.parse::() { 168 | Ok(Token::float(val, start, end)) 169 | } else { 170 | Err(Error::MalformedNumber(out, start)) 171 | } 172 | } 173 | 174 | fn lex_symbol(iter: &mut TokenIterator, character: char) -> Result { 175 | let mut result = vec![character]; 176 | let start = iter.get_location(); 177 | 178 | while let Some(&next_character) = iter.char_iter.peek() { 179 | match next_character { 180 | 'a'...'z' | 'A'...'Z' | '!' | '$' | '%' | '&' | '*' | '/' | ':' | '<' | '=' | '>' | 181 | '?' | '^' | '_' | '~' | '0'...'9' | '+' | '-' | '.' | '@' => { 182 | iter.step(EndOfLine::No, Move::Yes); 183 | result.push(next_character); 184 | } 185 | // Stop on whitespace or parentheses. 186 | '(' | ')' | ' ' | '\n' | '\t' | '\r' => break, 187 | _ => return Err(Error::InvalidCharacter(next_character, start)), 188 | } 189 | } 190 | 191 | iter.step(EndOfLine::No, Move::No); 192 | 193 | let out: String = result.iter().cloned().collect(); 194 | 195 | Ok(Token::symbol(out, start)) 196 | } 197 | 198 | fn lex_boolean(iter: &mut TokenIterator, character: char) -> Result { 199 | let mut result = vec![character]; 200 | let start = iter.get_location(); 201 | 202 | while let Some(&next_character) = iter.char_iter.peek() { 203 | match next_character { 204 | 'a'...'z' | 'A'...'Z' => { 205 | iter.step(EndOfLine::No, Move::Yes); 206 | result.push(next_character); 207 | } 208 | // Stop on whitespace or parentheses. 209 | '(' | ')' | ' ' | '\n' | '\t' | '\r' => break, 210 | _ => return Err(Error::InvalidCharacter(next_character, start)), 211 | } 212 | } 213 | 214 | iter.step(EndOfLine::No, Move::No); 215 | 216 | let out: String = result.iter().cloned().collect(); 217 | let end = iter.get_location(); 218 | 219 | if out == "#t" || out == "#true" { 220 | Ok(Token::boolean(true, start, end)) 221 | } else if out == "#f" || out == "#false" { 222 | Ok(Token::boolean(false, start, end)) 223 | } else { 224 | Err(Error::InvalidLiteral(out, start)) 225 | } 226 | } 227 | 228 | fn lex_string(iter: &mut TokenIterator, character: char) -> Result { 229 | let mut result = Vec::new(); 230 | let mut escape = false; 231 | let start = iter.get_location(); 232 | 233 | iter.string_context = true; 234 | 235 | while let Some(&next_character) = iter.char_iter.peek() { 236 | match next_character { 237 | '\\' if !escape => { 238 | escape = true; 239 | } 240 | '\\' if escape => { 241 | escape = false; 242 | iter.step(EndOfLine::No, Move::Yes); 243 | result.push('\\'); 244 | } 245 | 't' if escape => { 246 | escape = false; 247 | iter.step(EndOfLine::No, Move::Yes); 248 | result.push('\t'); 249 | } 250 | 'n' if escape => { 251 | escape = false; 252 | iter.step(EndOfLine::No, Move::Yes); 253 | result.push('\n'); 254 | } 255 | 'r' if escape => { 256 | escape = false; 257 | iter.step(EndOfLine::No, Move::Yes); 258 | result.push('\r'); 259 | } 260 | x if character == x && escape => { 261 | escape = false; 262 | iter.step(EndOfLine::No, Move::Yes); 263 | result.push(x) 264 | } 265 | x if character == x && !escape => { 266 | iter.step(EndOfLine::No, Move::Yes); 267 | break; 268 | } 269 | _ if escape => { 270 | let sequence = format!("\\{}", next_character); 271 | return Err(Error::InvalidEscapeSequence(sequence, iter.get_location())); 272 | } 273 | _ => { 274 | escape = false; 275 | iter.step(EndOfLine::No, Move::Yes); 276 | result.push(next_character); 277 | } 278 | } 279 | } 280 | 281 | iter.string_context = false; 282 | iter.step(EndOfLine::No, Move::No); 283 | 284 | let out: String = result.iter().cloned().collect(); 285 | Ok(Token::string(out, start)) 286 | } 287 | 288 | -------------------------------------------------------------------------------- /libruse-read/src/lib.rs: -------------------------------------------------------------------------------- 1 | #![feature(cell_update)] 2 | 3 | pub mod lex; 4 | pub mod parse; 5 | pub mod error; 6 | use error::Result; 7 | use lex::lex; 8 | use parse::parse; 9 | 10 | pub fn read>(program: S) -> Result { 11 | let tokens = lex(program)?; 12 | let ast = parse(tokens)?; 13 | Ok(ast) 14 | } 15 | 16 | -------------------------------------------------------------------------------- /libruse-read/src/parse/error.rs: -------------------------------------------------------------------------------- 1 | //! Parser error and result types. 2 | 3 | use parse::expr::Expr; 4 | 5 | use std::error; 6 | use std::fmt; 7 | use std::result; 8 | 9 | pub type Result = result::Result; 10 | 11 | #[derive(Debug, PartialEq)] 12 | pub enum Response { 13 | EmptyProgram, 14 | InvalidProgram, 15 | EndOfProgram, 16 | } 17 | 18 | impl error::Error for Response { 19 | fn description(&self) -> &str { 20 | match *self { 21 | Response::EmptyProgram => "empty program", 22 | Response::InvalidProgram => "invalid program", 23 | Response::EndOfProgram => "end of program", 24 | } 25 | } 26 | } 27 | 28 | impl fmt::Display for Response { 29 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 30 | write!(f, "{}", (self as &error::Error).description()) 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /libruse-read/src/parse/expr.rs: -------------------------------------------------------------------------------- 1 | use std::fs::File; 2 | use std::collections::HashMap; 3 | use std::default::Default; 4 | 5 | pub struct Expr { 6 | pub kind: ExprKind, 7 | pub marked: bool, 8 | pub mutable: bool, 9 | } 10 | 11 | impl Expr { 12 | pub fn new(kind: ExprKind) -> Expr { 13 | let marked = false; 14 | let mutable = false; 15 | 16 | Expr { kind, marked, mutable } 17 | } 18 | } 19 | 20 | pub enum ExprKind { 21 | Bool(bool), 22 | Char(char), 23 | Num(Number), 24 | Pair(Pair), 25 | Closure(Closure), 26 | Syntax(Syntax), 27 | Symbol(Symbol), 28 | Str(String), 29 | Vector(Vector), 30 | ByteVector(ByteVector), 31 | Continuation(Continuation), 32 | Port(Port), 33 | Env(Env), 34 | } 35 | 36 | #[allow(dead_code)] 37 | pub struct Env { 38 | symbols: HashMap, 39 | } 40 | 41 | impl Default for Env { 42 | fn default() -> Env { 43 | Env { 44 | symbols: HashMap::new(), 45 | } 46 | } 47 | } 48 | 49 | #[derive(Debug, PartialEq)] 50 | pub struct Number { 51 | pub exact: bool, 52 | pub kind: NumberKind, 53 | } 54 | 55 | #[derive(Debug, PartialEq)] 56 | pub enum NumberKind { 57 | Int(i64), 58 | Real(f64), 59 | Rational { 60 | numerator: i64, 61 | denominator: i64, 62 | } 63 | } 64 | 65 | pub struct Pair { 66 | pub car: Box, 67 | pub cdr: Box, 68 | } 69 | 70 | pub struct Closure { 71 | pub lambda: Box, 72 | pub env: Env, 73 | pub syntactic: bool, 74 | pub body: Box, 75 | pub args: Box, 76 | } 77 | 78 | pub type Lambda = Fn(Box, Box) -> Box; 79 | pub type Symbol = String; 80 | pub type Vector = Vec>; 81 | pub type ByteVector = Vec; 82 | 83 | pub struct Syntax { 84 | pub transformer: Box, 85 | pub env: Box, 86 | } 87 | 88 | // TODO: Implement continuations. 89 | #[derive(Debug, PartialEq)] 90 | pub struct Continuation {} 91 | 92 | #[derive(Debug)] 93 | pub struct Port { 94 | pub file: File, 95 | pub string: String, 96 | pub kind: PortKind, 97 | pub writable: bool, 98 | pub readable: bool, 99 | } 100 | 101 | #[derive(Debug, PartialEq, Eq)] 102 | pub enum PortKind { 103 | Textual, 104 | Binary, 105 | } 106 | 107 | -------------------------------------------------------------------------------- /libruse-read/src/parse/mod.rs: -------------------------------------------------------------------------------- 1 | //! Generate a syntax tree from an input stream. 2 | 3 | pub mod error; 4 | pub mod expr; 5 | 6 | pub use parse::error::{Response, Result}; 7 | use parse::expr::*; 8 | use lex::token::{Token, TokenKind}; 9 | use parse::expr::Expr; 10 | use std::slice::Iter; 11 | use std::iter::Peekable; 12 | 13 | pub fn parse>(v: V) -> Result { 14 | // TODO: Incorporate environment into parsing. 15 | let _env = Env::default(); 16 | let mut i = v.as_ref().iter().peekable(); 17 | parse_expr(&mut i) 18 | } 19 | 20 | macro_rules! unwrap_or_return { 21 | ( $e:expr, $r:expr ) => { 22 | match $e { 23 | Some(x) => x, 24 | None => return $r, 25 | } 26 | } 27 | } 28 | 29 | macro_rules! peek_or_stop { 30 | ( $e:expr ) => { 31 | unwrap_or_return!($e.peek(), Err(Response::EndOfProgram)); 32 | } 33 | } 34 | 35 | // A shorthand type, to make the below functions more readable. 36 | // 37 | // The iterator needs to be peekable so we can avoid moving the iterator 38 | // forward in the case of a failed parse. 39 | type Tokens<'a> = Peekable>; 40 | 41 | fn parse_expr(v: &mut Tokens) -> Result { 42 | if let Ok(a) = parse_symbol(v) { 43 | return Ok(a); 44 | } 45 | 46 | if let Ok(a) = parse_number(v) { 47 | return Ok(a); 48 | } 49 | 50 | if let Ok(a) = parse_float(v) { 51 | return Ok(a); 52 | } 53 | 54 | if let Ok(a) = parse_string(v) { 55 | return Ok(a); 56 | } 57 | 58 | if let Ok(a) = parse_bool(v) { 59 | return Ok(a); 60 | } 61 | 62 | if let Ok(a) = parse_list(v) { 63 | return Ok(a); 64 | } 65 | 66 | Err(Response::InvalidProgram) 67 | } 68 | 69 | fn parse_symbol(v: &mut Tokens) -> Result { 70 | let t = peek_or_stop!(v); 71 | 72 | if let TokenKind::Symbol(ref s) = t.kind { 73 | let kind = ExprKind::Symbol(s.clone()); 74 | let expr = Expr::new(kind); 75 | return Ok(expr); 76 | } 77 | 78 | Err(Response::InvalidProgram) 79 | } 80 | 81 | fn parse_number(v: &mut Tokens) -> Result { 82 | let t = peek_or_stop!(v); 83 | 84 | if let TokenKind::Integer(i) = t.kind { 85 | let value = Number { 86 | kind: NumberKind::Int(i), 87 | exact: true, 88 | }; 89 | let kind = ExprKind::Num(value); 90 | let expr = Expr::new(kind); 91 | return Ok(expr); 92 | } 93 | 94 | Err(Response::InvalidProgram) 95 | } 96 | 97 | fn parse_float(v: &mut Tokens) -> Result { 98 | let t = peek_or_stop!(v); 99 | 100 | if let TokenKind::Float(f) = t.kind { 101 | let value = Number { 102 | kind: NumberKind::Real(f), 103 | exact: true, 104 | }; 105 | let kind = ExprKind::Num(value); 106 | let expr = Expr::new(kind); 107 | return Ok(expr); 108 | } 109 | 110 | Err(Response::InvalidProgram) 111 | } 112 | 113 | fn parse_string(v: &mut Tokens) -> Result { 114 | let t = peek_or_stop!(v); 115 | 116 | if let TokenKind::Str(ref s) = t.kind { 117 | let kind = ExprKind::Str(s.clone()); 118 | let expr = Expr::new(kind); 119 | return Ok(expr); 120 | } 121 | 122 | Err(Response::InvalidProgram) 123 | } 124 | 125 | fn parse_bool(v: &mut Tokens) -> Result { 126 | let t = peek_or_stop!(v); 127 | 128 | if let TokenKind::Bool(b) = t.kind { 129 | let kind = ExprKind::Bool(b); 130 | let expr = Expr::new(kind); 131 | return Ok(expr); 132 | } 133 | 134 | Err(Response::InvalidProgram) 135 | } 136 | 137 | fn parse_list(v: &mut Tokens) -> Result { 138 | // Parse an opening delimiter, then a series of Ruse expressions 139 | // until you hit the matching closing delimiter. If you hit 140 | // a non-matching closing delimiter first, error out. 141 | let t = peek_or_stop!(v); 142 | 143 | if !t.kind.is_open_delim() { 144 | return Err(Response::InvalidProgram); 145 | } 146 | 147 | unimplemented!() 148 | } 149 | 150 | -------------------------------------------------------------------------------- /libruse/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "libruse" 3 | version = "0.1.0" 4 | authors = ["Andrew Brinker "] 5 | 6 | [dependencies] 7 | libruse-read = { path = "../libruse-read" } 8 | libruse-eval = { path = "../libruse-eval" } 9 | libruse-print = { path = "../libruse-print" } 10 | 11 | -------------------------------------------------------------------------------- /libruse/src/error.rs: -------------------------------------------------------------------------------- 1 | //! Types for handling errors in the ruse engine. 2 | 3 | use read; 4 | use std::error; 5 | use std::fmt; 6 | use std::result; 7 | 8 | /// The result of reading a string. 9 | pub type Result = result::Result; 10 | 11 | /// Indicates an error in lexing or parsing. 12 | #[derive(Debug, PartialEq)] 13 | pub enum Error { 14 | /// Indicates an error in reading. 15 | ReadError(read::error::Error), 16 | } 17 | 18 | impl error::Error for Error { 19 | /// Get a simple text description of what each error means. 20 | fn description(&self) -> &str { 21 | match *self { 22 | Error::ReadError(..) => "an error occured during reading", 23 | } 24 | } 25 | 26 | /// The underlying cause of the error. 27 | fn cause(&self) -> Option<&error::Error> { 28 | match *self { 29 | Error::ReadError(ref error) => Some(error), 30 | } 31 | } 32 | } 33 | 34 | impl fmt::Display for Error { 35 | /// Print detailed error information. 36 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 37 | match *self { 38 | Error::ReadError(ref error) => write!(f, "{}", error), 39 | } 40 | } 41 | } 42 | 43 | impl From for Error { 44 | /// Convert from a read::error into a top-level ruse Error. 45 | fn from(err: read::error::Error) -> Error { 46 | Error::ReadError(err) 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /libruse/src/lib.rs: -------------------------------------------------------------------------------- 1 | //! Ruse is an embedded Scheme for Rust. It is currently in the very early 2 | //! stages, and should not be used for anything. 3 | //! 4 | //! At the moment, Ruse is little more than a lexer and a work-in-progress 5 | //! parser. Long term, the goal is for Ruse to be an R7RS small-specification 6 | //! compliant version of Scheme for embedding in Rust programs. Ruse code will 7 | //! be able to call Rust code, and Rust code will be able to call Ruse. Their 8 | //! relationship should be akin to the relationship between Lua and C. 9 | //! 10 | //! This is obviously an amibitious project, and I don't know when/if Ruse will 11 | //! reach this point. But it's sure fun to play with! 12 | 13 | #![deny(missing_docs)] 14 | 15 | extern crate libruse_read as read; 16 | extern crate libruse_eval as eval; 17 | extern crate libruse_print as print; 18 | 19 | pub mod error; 20 | 21 | use std::path::Path; 22 | use std::fs::File; 23 | use std::io::Read; 24 | 25 | use error::Result; 26 | use read::read; 27 | use eval::eval; 28 | use print::print; 29 | 30 | /// The entry point for running Ruse programs. 31 | /// 32 | /// The engine is the main interface between Ruse and Rust. It is where 33 | /// Rust functions are registered, and where Ruse functions are run. 34 | /// 35 | /// Eventually the Engine will store all Rust-side function bindings, and 36 | /// provide a way for the user to register new bindings. There will also 37 | /// be a utility to register bindings on the Ruse side, to be callable 38 | /// from the Rust side. 39 | #[derive(Default)] 40 | pub struct Engine {} 41 | 42 | impl Engine { 43 | /// Create a new Engine. 44 | pub fn new() -> Engine { 45 | Default::default() 46 | } 47 | 48 | /// Run the engine on a specific program. 49 | pub fn run>(&mut self, s: S) -> Result { 50 | let r = read(s).unwrap(); 51 | let e = eval(r).unwrap(); 52 | let p = print(e).unwrap(); 53 | Ok(p) 54 | } 55 | 56 | /// Run the engine on a program from a file. 57 | /// 58 | /// TODO: Remove the unwrapping from this function. 59 | pub fn run_file>(&mut self, s: S) -> Result { 60 | let mut f = File::open(s).unwrap(); 61 | let mut buffer = String::new(); 62 | f.read_to_string(&mut buffer).expect("could not read file"); 63 | self.run(buffer) 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /ruse/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "ruse" 3 | version = "0.1.0" 4 | authors = ["Andrew Brinker "] 5 | 6 | [dependencies] 7 | clap = "2.32.0" 8 | libruse = { path = "../libruse" } 9 | 10 | -------------------------------------------------------------------------------- /ruse/src/main.rs: -------------------------------------------------------------------------------- 1 | //! The Ruse CLI 2 | 3 | #![deny(missing_docs)] 4 | 5 | extern crate libruse; 6 | extern crate clap; 7 | 8 | use libruse::Engine; 9 | use clap::{Arg, App}; 10 | 11 | fn main() { 12 | // TODO: Expand the CLI to do more. 13 | // 14 | // Ideally, the CLI would include the following structure: 15 | // 16 | // ruse help 17 | // ruse version 18 | // ruse exec "(+ 2 2)" 19 | // ruse exec --file hello.rus 20 | // ruse repl 21 | // ruse repl --with hello.rus blah.rus 22 | let matches = App::new("ruse") 23 | .version(env!("CARGO_PKG_VERSION")) 24 | .author("Ruse Language Developers") 25 | .about("An embedded Scheme for Rust") 26 | .arg( 27 | Arg::with_name("SOURCE") 28 | .help("The Ruse program to execute") 29 | .required(true) 30 | .index(1), 31 | ) 32 | .get_matches(); 33 | 34 | let source = matches.value_of("SOURCE").expect("No program provided."); 35 | 36 | let mut engine = Engine::new(); 37 | let result = engine.run(source); 38 | println!("{}", result.unwrap()); 39 | } 40 | --------------------------------------------------------------------------------