Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create boilerplate for popular languages #151

Merged
merged 5 commits into from
Apr 29, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
[package]
name = "discord-compiler-bot"
description = "Discord bot to compile your spaghetti code."
version = "3.3.3"
version = "3.4.0"
authors = ["Michael Flaherty (Headline#9999)"]
edition = "2018"
build = "src/build.rs"
Expand Down
52 changes: 52 additions & 0 deletions src/boilerplate/cpp.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
use regex::Regex;
use crate::boilerplate::generator::BoilerPlateGenerator;

pub struct CppGenerator {
input : String
}

impl BoilerPlateGenerator for CppGenerator {
fn new(input: &str) -> Self {
let mut formated = input.to_string();
formated = formated.replace(";", ";\n"); // separate lines by ;

Self {
input : formated
}
}

fn generate(&self) -> String {
let mut main_body = String::default();
let mut header = String::default();

let mut lines = self.input.split("\n");
while let Some(line) = lines.next() {
let trimmed = line.trim();
if trimmed.starts_with("using") {
header.push_str(&format!("{}\n", trimmed));
}
else if trimmed.starts_with("#i") {
header.push_str(&format!("{}\n", trimmed));
}
else {
main_body.push_str(&format!("{}\n", trimmed))
}
}

// if they included nothing, we can just manually include everything
if !header.contains("#include") {
header.push_str("#include <bits/stdc++.h>");
}
format!("{}\nint main(void) {{\n{}return 0;\n}}", header, main_body)
}

fn needs_boilerplate(&self) -> bool {
let cpp_main_regex: Regex = Regex::new("\"[^\"]+\"|(?P<main>main[\\s]*?\\()").unwrap();
for m in cpp_main_regex.captures_iter(&self.input) {
if let Some(_) = m.name("main") {
return false;
}
}
return true;
}
}
49 changes: 49 additions & 0 deletions src/boilerplate/csharp.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
use regex::Regex;
use crate::boilerplate::generator::BoilerPlateGenerator;

pub struct CSharpGenerator {
input : String
}

impl BoilerPlateGenerator for CSharpGenerator {
fn new(input: &str) -> Self {
let mut formated = input.to_string();
formated = formated.replace(";", ";\n"); // separate lines by ;

Self {
input : formated
}
}

fn generate(&self) -> String {
let mut main_body = String::default();
let mut header = String::default();

let mut lines = self.input.split("\n");
while let Some(line) = lines.next() {
let trimmed = line.trim();
if trimmed.starts_with("using") {
header.push_str(&format!("{}\n", trimmed));
}
else {
main_body.push_str(&format!("{}\n", trimmed))
}
}

// if they included nothing, we can just manually include System since they probably want it
if header.is_empty() {
header.push_str("using System;");
}
format!("{}\nnamespace Main{{\nclass Program {{\n static void Main(string[] args) {{\n{}}}}}}}", header, main_body)
}

fn needs_boilerplate(&self) -> bool {
let cpp_main_regex: Regex = Regex::new("\"[^\"]+\"|(?P<main>static[\\s]+?void[\\s]+?Main[\\s]*?\\()").unwrap();
for m in cpp_main_regex.captures_iter(&self.input) {
if let Some(_) = m.name("main") {
return false;
}
}
return true;
}
}
64 changes: 64 additions & 0 deletions src/boilerplate/generator.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
use crate::boilerplate::cpp::CppGenerator;
use crate::boilerplate::csharp::CSharpGenerator;
use crate::boilerplate::java::JavaGenerator;

pub trait BoilerPlateGenerator {
fn new(input : &str) -> Self where Self: Sized;
fn generate(&self) -> String;
fn needs_boilerplate(&self) -> bool;
}

pub struct BoilerPlate<T: ?Sized> where T: BoilerPlateGenerator {
generator : Box<T>
}

impl<T: ?Sized> BoilerPlate<T> where T: BoilerPlateGenerator{
pub fn new(generator : Box<T>) -> Self {
Self {
generator
}
}

pub fn generate(&self) -> String {
self.generator.generate()
}

pub fn needs_boilerplate(&self) -> bool {
self.generator.needs_boilerplate()
}
}

pub struct Null;
impl BoilerPlateGenerator for Null {
fn new(_: &str) -> Self {
Self {}
}

fn generate(&self) -> String {
panic!("Cannot generate null boilerplate!");
}

fn needs_boilerplate(&self) -> bool {
false
}
}

pub fn boilerplate_factory(language : &str, code : &str)
-> BoilerPlate<dyn BoilerPlateGenerator> {
return match language {
"c++" | "c" => {
BoilerPlate::new(Box::new(CppGenerator::new(code)))
}
"java" => {
BoilerPlate::new(Box::new(JavaGenerator::new(code)))
}
"c#" => {
BoilerPlate::new(Box::new(CSharpGenerator::new(code)))
}
// since all compilations go through this path, we have a Null generator whose
// needs_boilerplate() always returns false.
_ => {
BoilerPlate::new(Box::new(Null::new(code)))
}
}
}
45 changes: 45 additions & 0 deletions src/boilerplate/java.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
use regex::Regex;
use crate::boilerplate::generator::BoilerPlateGenerator;

pub struct JavaGenerator {
input : String
}

impl BoilerPlateGenerator for JavaGenerator {
fn new(input: &str) -> Self {
let mut formated = input.to_string();
formated = formated.replace(";", ";\n"); // separate lines by ;

Self {
input : formated
}
}

fn generate(&self) -> String {
let mut main_body = String::default();
let mut header = String::default();

let mut lines = self.input.split("\n");
while let Some(line) = lines.next() {
let trimmed = line.trim();
if trimmed.starts_with("import") {
header.push_str(&format!("{}\n", trimmed));
}
else {
main_body.push_str(&format!("{}\n", trimmed))
}
}

format!("{}\nclass Main{{\npublic static void main(String[] args) {{\n{}}}}}", header, main_body)
}

fn needs_boilerplate(&self) -> bool {
let java_main_regex: Regex = Regex::new("\"[^\"]+\"|(?P<main>public[\\s]+?static[\\s]+?void[\\s]+?main[\\s]*?\\()").unwrap();
for m in java_main_regex.captures_iter(&self.input) {
if let Some(_) = m.name("main") {
return false;
}
}
return true;
}
}
4 changes: 4 additions & 0 deletions src/boilerplate/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
pub mod generator;
pub mod cpp;
pub mod java;
pub mod csharp;
1 change: 1 addition & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ mod cppeval;
mod managers;
mod tests;
mod slashcmds;
mod boilerplate;

use serenity::{
framework::{standard::macros::group, StandardFramework},
Expand Down
39 changes: 37 additions & 2 deletions src/managers/compilation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use serenity::builder::CreateEmbed;

use wandbox::{Wandbox, CompilationBuilder, WandboxError};
use godbolt::{Godbolt, GodboltError, CompilationFilters, RequestOptions, CompilerOptions};
use crate::boilerplate::generator::{boilerplate_factory};

use crate::utls::parser::ParserResult;
use crate::utls::discordhelpers::embeds::ToEmbed;
Expand Down Expand Up @@ -138,7 +139,16 @@ impl CompilationManager {

let target = if parse_result.target == "haskell" { "ghc901" } else { &parse_result.target };
let compiler = self.gbolt.resolve(target).unwrap();
let response = Godbolt::send_request(&compiler, &parse_result.code, options, USER_AGENT).await?;

// replace boilerplate code if needed
let mut code = parse_result.code.clone();
{
let generator = boilerplate_factory(&compiler.lang, &code);
if generator.needs_boilerplate() {
code = generator.generate();
}
}
let response = Godbolt::send_request(&compiler, &code, options, USER_AGENT).await?;
Ok((compiler.lang, response))
}

Expand All @@ -162,8 +172,33 @@ impl CompilationManager {
}

pub async fn wandbox(&self, parse_result : &ParserResult) -> Result<(String, wandbox::CompilationResult), WandboxError> {
let lang = {
let mut found = String::default();
for lang in self.wbox.get_languages() {
if parse_result.target == lang.name {
found = parse_result.target.clone();
}
for compiler in lang.compilers {
if compiler.name == parse_result.target {
found = lang.name.clone();
}
}
}
if found.is_empty() {
warn!("Invalid target leaked checks and was caught before boilerplate creation")
}
found
};
let mut code = parse_result.code.clone();
{
let generator = boilerplate_factory(&lang, &code);
if generator.needs_boilerplate() {
code = generator.generate();
}
}

let mut builder = CompilationBuilder::new();
builder.code(&parse_result.code);
builder.code(&code);
builder.target(&parse_result.target);
builder.stdin(&parse_result.stdin);
builder.save(false);
Expand Down
2 changes: 1 addition & 1 deletion src/utls/constants.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ pub const ICON_INVITE: &str = "https://i.imgur.com/CZFt69d.png";
//pub const COMPILER_EXPLORER_ICON: &str = "https://i.imgur.com/GIgATFr.png";
pub const COMPILER_ICON: &str = "http://i.michaelwflaherty.com/u/XedLoQWCVc.png";
pub const MAX_OUTPUT_LEN: usize = 250;
pub const MAX_ERROR_LEN: usize = 956;
pub const MAX_ERROR_LEN: usize = 997;
pub const USER_AGENT : &str = const_format::formatcp!("discord-compiler-bot/{}", env!("CARGO_PKG_VERSION"));
pub const URL_ALLOW_LIST : [&str; 4] = ["pastebin.com", "gist.githubusercontent.com", "hastebin.com", "raw.githubusercontent.com"];

Expand Down