From 325ffc2a2c840b3a858d7cf55da4b7682292ff16 Mon Sep 17 00:00:00 2001 From: Owen Nelson Date: Sun, 9 Dec 2018 23:30:51 +0100 Subject: [PATCH] Add support for Rust 2018 edition projects. Summary: After enabling 2018 edition on my cargo project, the use statements generated in the interface module no longer resolve. Prefixing module paths with `crate::` brings things back into alignment. Unsure if this is how you'd like to approach the issue, but I'm happy to revise the patch based on your feedback. Test Plan: STEPS TO REPRODUCE 1. create a new cargo project based on the template 2. update your toolchain to >= 1.31 3. add `edition = "2018"` to the package section of your Cargo.toml 4. run `cargo build` OBSERVED RESULT Build fails since generated code tries to import crate-local modules as if they are top level crates. EXPECTED RESULT Build completes successfully. Reviewers: vandenoever Differential Revision: https://phabricator.kde.org/D17447 --- Cargo.toml | 1 + src/configuration.rs | 28 ++++++++++++++++++++++++++++ src/lib.rs | 1 + src/rust.rs | 19 +++++++++++++++++-- 4 files changed, 47 insertions(+), 2 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 26becd0..c43c5da 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -16,3 +16,4 @@ serde = "1.0" serde_derive = "1.0" serde_json = "1.0" serde-xml-rs = "0.2.1" +toml = "0.4.10" \ No newline at end of file diff --git a/src/configuration.rs b/src/configuration.rs index 1ac9bc7..4daaef1 100644 --- a/src/configuration.rs +++ b/src/configuration.rs @@ -1,5 +1,6 @@ use configuration_private::*; use serde_json; +use toml; use std::collections::{BTreeMap, BTreeSet}; use std::error::Error; use std::fs; @@ -57,11 +58,28 @@ mod json { } } +pub enum RustEdition { + Rust2015, + Rust2018, + Unknown +} + +impl ::std::convert::From> for RustEdition { + fn from(str: Option<&str>) -> RustEdition { + match str { + None | Some("2015") => RustEdition::Rust2015, + Some("2018") => RustEdition::Rust2018, + _ => RustEdition::Unknown, + } + } +} + pub struct Config { pub config_file: PathBuf, pub cpp_file: PathBuf, pub objects: BTreeMap>, pub rust: Rust, + pub rust_edition: RustEdition, pub overwrite_implementation: bool, } @@ -447,11 +465,21 @@ fn post_process(config_file: &Path, json: json::Config) -> Result Result<()> { "#![allow(unused_imports)] #![allow(unused_variables)] #![allow(dead_code)] -use {}::*; +use {}{}::*; ", + get_module_prefix(conf), conf.rust.interface_module )?; @@ -1528,3 +1530,16 @@ use {}::*; } write_if_different(file, &r) } + +/// Inspects the rust edition of the target crate to decide how the module +/// imports should be written. +/// +/// As of Rust 2018, modules inside the crate should be prefixed with `crate::`. +/// Prior to the 2018 edition, crate-local modules could be imported without +/// this prefix. +fn get_module_prefix(conf: &Config) -> &'static str { + match conf.rust_edition { + RustEdition::Rust2018 => "crate::", + _ => "" + } +}