From add6ca08771379bbf5eb13610bec1cbe7af32db8 Mon Sep 17 00:00:00 2001 From: Quadellupine <annabella.gethke@hu-berlin.de> Date: Sun, 7 May 2023 09:46:53 +0200 Subject: [PATCH] Rust instead --- Cargo.toml | 8 ++ README.md | 177 +++++++++++++++++++---------------- src/lib.rs | 21 +++++ src/stack.rs | 108 +++++++++++++++++++++ src/syntax_tree.rs | 229 +++++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 464 insertions(+), 79 deletions(-) create mode 100644 Cargo.toml create mode 100644 src/lib.rs create mode 100644 src/stack.rs create mode 100644 src/syntax_tree.rs diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..4087388 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "cb-1" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/README.md b/README.md index a8ae6c2..61371d4 100644 --- a/README.md +++ b/README.md @@ -1,92 +1,111 @@ -# Aufgabe1_Compilerbau +# Übungsblatt 1 +## Generelles +Die ersten beiden Aufgaben dienen zur Vertiefung Ihrer praktischen Erfahrungen in Rust. Sie implementieren einen Stack und eine Baumstruktur. +## Allgemeine Hinweise +Für diese und alle folgenden Praktikumsaufgaben gilt, dass Einsendungen, die in der jeweils mitgegebenen Testumgebung nicht laufen, entsprechend Punktabzug erhalten! Das beinhaltet insbesondere alle Programme, die sich nicht fehlerfrei kompilieren lassen. Da Cargo für die Ausführung verantwortlich ist, sollte das Projekt bei Ihnen am Ende mit `cargo test` ohne Fehler und Warnungen durchlaufen. -## Getting started -To make it easy for you to get started with GitLab, here's a list of recommended next steps. +## Abgabemodus +Die Lösung ist in einem eigenen Git-Repository abzugeben. +Sie können in ihrer Lösung jedoch beliebige Hilfstypen und Module selbst definieren. +Die grundlegende Struktur des hier mitgegebenen Templates sollte jedoch nicht verändert werden. +Insbesondere ist es wichtig, dass die öffentliche Schnittstelle der Library, welche über die Signaturen der Methoden und Funktionen und deren absoluten Pfad definiert wird, nicht verändert wird. -Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)! +Zur Lösung der Aufgaben steht für Sie dieses Repository mit +- vorgegebenen Modulen [stack](src/stack.rs) und [syntax_tree](src/syntax_tree.rs) +- der vorgegebenen Schnittstelle der Library in [lib](src/lib.rs) +- einer Reihe von Testfällen (Unit-Tests) innerhalb der Module -## Add your files +zur Verfügung. +> Sie können die Implementierung mit `cargo test` prüfen. Mit `cargo test -- --nocapture` werden Konsolenausgaben auch bei korrekten Tests angezeigt. -- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files -- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command: +## Aufgabe 1 (50 Punkte) +### Kurzbeschreibung +Implementieren Sie einen Stack, der beliebig viele Integerzahlen speichern kann ("beliebig viel" bedeutet für uns: lediglich begrenzt durch den Arbeitsspeicher). Erweitern Sie dabei eine vorgegebene Schnittstelle (Stack Trait), sodass Ihr Stack in andere (bereits existierende) Programme eingebunden werden kann. -``` -cd existing_repo -git remote add origin https://scm.cms.hu-berlin.de/gethkean/aufgabe1_compilerbau.git -git branch -M main -git push -uf origin main -``` - -## Integrate with your tools - -- [ ] [Set up project integrations](https://scm.cms.hu-berlin.de/gethkean/aufgabe1_compilerbau/-/settings/integrations) - -## Collaborate with your team - -- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/) -- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html) -- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically) -- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/) -- [ ] [Automatically merge when pipeline succeeds](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html) - -## Test and Deploy - -Use the built-in continuous integration in GitLab. - -- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html) -- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing(SAST)](https://docs.gitlab.com/ee/user/application_security/sast/) -- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html) -- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/) -- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html) - -*** - -# Editing this README - -When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thank you to [makeareadme.com](https://www.makeareadme.com/) for this template. +### Aufgabenstellung +Wie sie in [lib](src/lib.rs) sehen können, betrachten wir einen Stack als eine Datenstruktur, auf der folgende Operationen ausgeführt werden können: -## Suggestions for a good README -Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information. +```rust +pub trait Stack { + /// Initialisiere einen leeren Stack + fn init() -> Self; -## Name -Choose a self-explaining name for your project. + /// Füge einen neuen Wert zum Stack hinzu + fn push_val(&mut self, i: i32); -## Description -Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors. + /// Lese den obersten Wert, ohne diesen zu entfernen + fn top_val(&self) -> Option<&i32>; -## Badges -On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge. + /// Entferne den obersten Wert und gib diesen zurück + fn pop_val(&mut self) -> Option<i32>; -## Visuals -Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method. - -## Installation -Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection. - -## Usage -Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README. - -## Support -Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc. - -## Roadmap -If you have ideas for releases in the future, it is a good idea to list them in the README. - -## Contributing -State if you are open to contributions and what your requirements are for accepting them. - -For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self. - -You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser. - -## Authors and acknowledgment -Show your appreciation to those who have contributed to the project. - -## License -For open source projects, say how it is licensed. - -## Project status -If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers. + /// Prüfe ob der Stack leer ist + fn is_empty(&self) -> bool; +} +``` +- Implementieren Sie den Stack-Trait in [stack.rs](src/stack.rs) für `ListStack` und für `Vec<T>` + +#### a) Implementierung für Vec<T> (10 Punkte) +- Implementieren Sie den Trait für Vec<T> +- Da Vec<T> bereits selbst über die Methoden eines Stack verfügt, muss hier lediglich an Vec delegiert werden. + +#### b) Implementierung für ListStack (40 Punkte) +- Vervollständigen Sie die Implementierung von Stack für ListStack +- Die Implementierung erfordert den Smart-Pointer `Box<T>`, um den rekursiven Typ sicher zu definieren. Eine Erklärung hierzu finden Sie im [Buch](https://doc.rust-lang.org/book/ch15-01-box.html) +- Zusätzlich wird ein Option<T> benötigt, um Werte mit [take](https://doc.rust-lang.org/std/option/enum.Option.html#method.take) auszutauschen + + +## Aufgabe 2 (50 Punkte) +### Kurzbeschreibung +Implementieren Sie eine Datenstruktur, die beliebig verzweigte Bäume speichern kann, mit den im Folgenden beschriebenen Methoden. + +### Aufgabenstellung +Die hier von Ihnen zu implementierende Datenstruktur dient der Repräsentation eines abstrakten Syntaxbaumes. + +```rust +struct SyntaxTree; + +impl<T> SyntaxTree<T> { + /// Create a SyntaxTree with a root node that carries the given value + pub fn new(value: T) -> SyntaxTree<T> { + todo!() + } + + /// Add another SyntaxTree as last child of this tree + pub fn push_node(&mut self, new_node: SyntaxTree<T>) { + todo!() + } + + /// Add another SyntaxTree as first child of this tree + pub fn prepend_node(&mut self, new_node: SyntaxTree<T>) { + todo!() + } + + /// Insert the given SyntaxTree into the children of this tree at the given index + pub fn insert_node(&mut self, index: usize, new_node: SyntaxTree<T>) { + todo!() + } + + /// Perform a depth-first search with the given predicate. + /// The method returns a reference to the first SyntaxTree instance for which the predicate + /// return true. If no instance is found, None is returned. + pub fn find_node(&self, predicate: fn(&SyntaxTree<T>) -> bool) -> Option<&SyntaxTree<T>> { + todo!() + } + + /// Perform a depth-first search with the given predicate. + /// The method returns a mutable reference to the first SyntaxTree instance for which the predicate + /// return true. If no instance is found, None is returned. + pub fn find_node_mut( + &mut self, + predicate: fn(&SyntaxTree<T>) -> bool, + ) -> Option<&SyntaxTree<T>> { + todo!() + } +} +``` +- Die zu implementierende Datenstruktur SyntaxTree soll Baumknoten in beliebig komplexen Konfigurationen speichern können und davon beliebig viele. +- Vervollständigen Sie die Implementierung in der Datei [syntax_tree](src/syntax_tree.rs). diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..c77fcf9 --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,21 @@ +mod stack; +mod syntax_tree; + +pub trait Stack { + fn init() -> Self; + + fn push_val(&mut self, i: i32); + + fn top_val(&self) -> Option<&i32>; + + fn pop_val(&mut self) -> Option<i32>; + + fn is_empty(&self) -> bool; +} + +pub use stack::ListStack; +pub use syntax_tree::SyntaxTree; +pub use syntax_tree::ID; + +#[cfg(test)] +mod tests {} diff --git a/src/stack.rs b/src/stack.rs new file mode 100644 index 0000000..2d3f449 --- /dev/null +++ b/src/stack.rs @@ -0,0 +1,108 @@ +use crate::Stack; + +// TODO Complete implementation +impl Stack for Vec<i32> { + fn init() -> Self { + todo!() + } + + fn push_val(&mut self, i: i32) { + todo!() + } + + fn top_val(&self) -> Option<&i32> { + todo!() + } + + fn pop_val(&mut self) -> Option<i32> { + todo!() + } + + fn is_empty(&self) -> bool { + todo!() + } +} + +#[derive(Debug)] +pub enum ListStack { + Val(i32, Option<Box<ListStack>>), + Nil, +} + +use ListStack::Nil; +use ListStack::Val; + +// Complete implementation of Stack for ListStack +impl Stack for ListStack { + fn init() -> Self { + Nil + } + + fn push_val(&mut self, i: i32) { + match self { + Val(value, other) => *self = todo!(), + Nil => *self = todo!(), + }; + } + + fn top_val(&self) -> Option<&i32> { + todo!() + } + + fn pop_val(&mut self) -> Option<i32> { + match self { + Val(value, other) => { + let popped_value = *value; + match other.take() { + None => *self = Nil, + Some(other) => todo!(), + }; + todo!() + } + Nil => None, + } + } + + fn is_empty(&self) -> bool { + todo!() + } +} + +#[cfg(test)] +mod tests { + use crate::stack::ListStack; + use crate::Stack; + use std::fmt::Debug; + + #[test] + fn vec_fill_and_clear() { + println! {"Testing Vec<T>"} + fill_and_clear_impl(Vec::init()); + } + + #[test] + fn linked_fill_and_clear() { + println! {"Testing ListStack"} + fill_and_clear_impl(ListStack::init()); + } + + fn fill_and_clear_impl<T: Stack + Debug>(mut stack: T) { + stack.push_val(1); + assert_eq!(stack.top_val(), Some(&1)); + + stack.push_val(2); + assert_eq!(stack.top_val(), Some(&2)); + + stack.push_val(-3); + assert_eq!(stack.top_val(), Some(&-3)); + + println!("{:?}", stack); + + let mut comparison = vec![1, 2, -3]; + while let Some(val) = stack.pop_val() { + assert_eq!(comparison.pop().unwrap(), val); + } + + assert!(stack.is_empty()) + } +} diff --git a/src/syntax_tree.rs b/src/syntax_tree.rs new file mode 100644 index 0000000..6d70c91 --- /dev/null +++ b/src/syntax_tree.rs @@ -0,0 +1,229 @@ +use std::fmt::{Display, Formatter}; + +pub type ID = usize; + +static mut LAST_ID: usize = 0; + +#[derive(Clone, Debug, PartialEq)] +pub struct SyntaxTree<T> { + id: ID, + value: T, + children: Vec<SyntaxTree<T>>, +} + +/// Simple ID provider +fn next_id() -> ID { + unsafe { + let id = LAST_ID; + LAST_ID += 1; + id + } +} + +impl<T> SyntaxTree<T> { + /// Create a SyntaxTree with a root node that carries the given value + pub fn new(value: T) -> SyntaxTree<T> { + todo!() + } + + /// Add another SyntaxTree as last child of this tree + pub fn push_node(&mut self, new_node: SyntaxTree<T>) { + todo!() + } + + /// Create a new SyntaxTree with a root node that carries the given value. Add the created tree + /// as last child of this tree. + pub fn push_value(&mut self, value: T) { + self.push_node(SyntaxTree::new(value)); + } + + /// Add another SyntaxTree as first child of this tree + pub fn prepend_node(&mut self, new_node: SyntaxTree<T>) { + todo!() + } + + /// Create a new SyntaxTree with a root node that carries the given value. Add the created tree + /// as first child of this tree. + pub fn prepend_value(&mut self, value: T) { + self.prepend_node(SyntaxTree::new(value)); + } + + /// Insert the given SyntaxTree into the children of this tree at the given index + pub fn insert_node(&mut self, index: usize, new_node: SyntaxTree<T>) { + self.children.insert(index, new_node); + } + + /// Create a new SyntaxTree with a root node that carries the given value. + /// Insert the created SyntaxTree into the children of this tree at the given index + pub fn insert_value(&mut self, index: usize, value: T) { + self.insert_node(index, SyntaxTree::new(value)); + } + + /// Perform a depth-first search with the given predicate. + /// The method returns a reference to the first SyntaxTree instance for which the predicate + /// return true. If no instance is found, None is returned. + pub fn find_node(&self, predicate: fn(&SyntaxTree<T>) -> bool) -> Option<&SyntaxTree<T>> { + if predicate(self) { + Some(self) + } else { + todo!() + } + } + + /// Perform a depth-first search with the given predicate. + /// The method returns a mutable reference to the first SyntaxTree instance for which the predicate + /// return true. If no instance is found, None is returned. + pub fn find_node_mut( + &mut self, + predicate: fn(&SyntaxTree<T>) -> bool, + ) -> Option<&SyntaxTree<T>> { + todo!() + } + + /// Return a reference to the value carried by the root of this tree + pub fn value(&self) -> &T { + &self.value + } + + /// Return the id of the root of this tree + pub fn id(&self) -> ID { + self.id + } + + /// Return a reference to the children of this tree + pub fn children(&self) -> &Vec<SyntaxTree<T>> { + &self.children + } +} + +impl<T: Display> SyntaxTree<T> { + pub fn print(&self) -> String { + if self.children.is_empty() { + format!("{}", self.value) + } else { + format!( + "{}\n[\n{}\n]", + self.value, + &self + .children + .iter() + .map(|tn| tn.print_inner(1)) + .collect::<Vec<String>>() + .join(",\n") + ) + } + } + + pub fn print_inner(&self, indent: usize) -> String { + let mut indentation = String::new(); + for _ in 0..indent { + indentation.push_str(" "); + } + if self.children.is_empty() { + format!("{}{}", &indentation, self.value) + } else { + format!( + "{}{}\n{}[\n{}\n{}]", + &indentation, + self.value, + &indentation, + &self + .children + .iter() + .map(|tn| tn.print_inner(indent + 1)) + .collect::<Vec<String>>() + .join(",\n"), + indentation, + ) + } + } +} + +impl<T: Display> Display for SyntaxTree<T> { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + write!(f, "({})", self.print()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn fill_tree_numbers() -> SyntaxTree<i32> { + let mut tree = SyntaxTree::new(0); + + for child in 1..3 { + let mut child = SyntaxTree::new(child); + for grandchild in 1..3 { + let id = grandchild * 10; + child.prepend_node(SyntaxTree::new(id)); + } + tree.push_node(child); + } + tree + } + + fn fill_tree_words() -> SyntaxTree<String> { + let mut tree = SyntaxTree::new(to_s("root")); + + for (child_id, child) in ["first", "second", "third"].iter().map(to_s).enumerate() { + let child_id = child_id; + let mut child = SyntaxTree::new(child); + if child_id == 0 { + let mut descendant1 = SyntaxTree::new(to_s("A")); + let mut descendant2 = SyntaxTree::new(to_s("B")); + let descendant3 = SyntaxTree::new(to_s("C")); + descendant2.push_node(descendant3); + descendant1.push_node(descendant2); + child.push_node(descendant1); + } + tree.push_node(child); + } + tree + } + + #[test] + fn number_tree() -> Result<(), String> { + let tree = fill_tree_numbers(); + + println!("{}", tree); + assert_eq!( + String::from( + "0\n[\n 1\n [\n 20,\n 10\n ],\n 2\n [\n 20,\n 10\n ]\n]" + ), + tree.print() + ); + Ok(()) + } + + #[test] + fn word_tree() -> Result<(), String> { + let tree = fill_tree_words(); + + println!("{}", tree); + assert_eq!( + String::from("root\n[\n first\n [\n A\n [\n B\n [\n C\n ]\n ]\n ],\n second,\n third\n]"), + tree.print() + ); + Ok(()) + } + + #[test] + fn find_node_by_value() -> Result<(), String> { + let tree = fill_tree_numbers(); + + assert!(tree.find_node(|n| n.value == 0).is_some()); + let left = tree.find_node(|n| n.value == 1).unwrap(); + assert!(left.find_node(|n| n.value == 10).is_some()); + assert!(left.find_node(|n| n.value == 20).is_some()); + + let right = tree.find_node(|n| n.value == 2).unwrap(); + assert!(right.find_node(|n| n.value == 10).is_some()); + assert!(right.find_node(|n| n.value == 20).is_some()); + Ok(()) + } + + fn to_s<T: Display>(value: T) -> String { + format!("{}", value) + } +} -- GitLab