commit 087c6ce1e872659fb3e0069d4e5ff47e96876311 Author: Luke Street Date: Sat Sep 3 08:47:21 2022 -0400 Initial commit diff --git a/.github/workflows/build.yaml b/.github/workflows/build.yaml new file mode 100644 index 0000000..ceb7d24 --- /dev/null +++ b/.github/workflows/build.yaml @@ -0,0 +1,60 @@ +name: Build + +on: [ push, pull_request ] + +jobs: + check: + name: Check + runs-on: ubuntu-latest + strategy: + matrix: + toolchain: [ stable, 1.51.0, nightly ] + env: + RUSTFLAGS: -D warnings + steps: + - uses: actions/checkout@v2 + - uses: actions-rs/toolchain@v1 + with: + profile: minimal + toolchain: ${{ matrix.toolchain }} + override: true + components: rustfmt, clippy + - uses: EmbarkStudios/cargo-deny-action@v1 + - uses: actions-rs/cargo@v1 + with: + command: check + args: --all-features + - uses: actions-rs/cargo@v1 + with: + command: clippy + args: --all-features + + build: + name: Build + strategy: + matrix: + platform: [ ubuntu-latest, macos-latest, windows-latest ] + toolchain: [ stable, 1.51.0, nightly ] + fail-fast: false + runs-on: ${{ matrix.platform }} + steps: + - uses: actions/checkout@v2 + - uses: actions-rs/toolchain@v1 + with: + profile: minimal + toolchain: ${{ matrix.toolchain }} + override: true + - uses: actions-rs/cargo@v1 + with: + command: test + args: --release --all-features + - uses: actions-rs/cargo@v1 + with: + command: build + args: --release --all-features + - uses: actions/upload-artifact@v2 + with: + name: ${{ matrix.platform }}-${{ matrix.toolchain }} + path: | + target/release/cwdemangle + target/release/cwdemangle.exe diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b471067 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +/target +Cargo.lock +.idea diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..d82169f --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "cwdemangle" +version = "0.1.0" +edition = "2021" +authors = ["Luke Street "] +license = "MIT OR Apache-2.0" +repository = "https://github.com/encounter/cwdemangle" +readme = "README.md" +description = """ +CodeWarrior C++ symbol demangler +""" +categories = ["command-line-utilities"] + +[dependencies] +argh = "0.1.8" diff --git a/LICENSE-APACHE b/LICENSE-APACHE new file mode 100644 index 0000000..e9d5437 --- /dev/null +++ b/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2021 Luke Street. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/LICENSE-MIT b/LICENSE-MIT new file mode 100644 index 0000000..5bf95a4 --- /dev/null +++ b/LICENSE-MIT @@ -0,0 +1,21 @@ +MIT License + +Copyright 2021 Luke Street. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..fedb63b --- /dev/null +++ b/README.md @@ -0,0 +1,43 @@ +# cwdemangle [![Build Status]][actions] + +[Build Status]: https://github.com/encounter/cwdemangle/workflows/build/badge.svg +[actions]: https://github.com/encounter/cwdemangle/actions + +CodeWarrior C++ symbol demangler. + +### Usage + +CLI: + +```shell +cwdemangle 'BuildLight__9CGuiLightCFv' +``` + +Library + +```rust +use cwdemangle::demangle; + +let symbol = "BuildLight__9CGuiLightCFv"; +if let Some(result) = demangle(symbol) { + println!("{}", result); + Ok(()) +} else { + Err("Couldn't demangle symbol (not a C++ symbol?)") +} +``` + +### License + +Licensed under either of + +* Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) +* MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) + +at your option. + +### Contribution + +Unless you explicitly state otherwise, any contribution intentionally submitted +for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any +additional terms or conditions. diff --git a/deny.toml b/deny.toml new file mode 100644 index 0000000..12d337b --- /dev/null +++ b/deny.toml @@ -0,0 +1,204 @@ +# This template contains all of the possible sections and their default values + +# Note that all fields that take a lint level have these possible values: +# * deny - An error will be produced and the check will fail +# * warn - A warning will be produced, but the check will not fail +# * allow - No warning or error will be produced, though in some cases a note +# will be + +# The values provided in this template are the default values that will be used +# when any section or field is not specified in your own configuration + +# If 1 or more target triples (and optionally, target_features) are specified, +# only the specified targets will be checked when running `cargo deny check`. +# This means, if a particular package is only ever used as a target specific +# dependency, such as, for example, the `nix` crate only being used via the +# `target_family = "unix"` configuration, that only having windows targets in +# this list would mean the nix crate, as well as any of its exclusive +# dependencies not shared by any other crates, would be ignored, as the target +# list here is effectively saying which targets you are building for. +targets = [ + # The triple can be any string, but only the target triples built in to + # rustc (as of 1.40) can be checked against actual config expressions + #{ triple = "x86_64-unknown-linux-musl" }, + # You can also specify which target_features you promise are enabled for a + # particular target. target_features are currently not validated against + # the actual valid features supported by the target architecture. + #{ triple = "wasm32-unknown-unknown", features = ["atomics"] }, +] + +# This section is considered when running `cargo deny check advisories` +# More documentation for the advisories section can be found here: +# https://embarkstudios.github.io/cargo-deny/checks/advisories/cfg.html +[advisories] +# The path where the advisory database is cloned/fetched into +db-path = "~/.cargo/advisory-db" +# The url(s) of the advisory databases to use +db-urls = ["https://github.com/rustsec/advisory-db"] +# The lint level for security vulnerabilities +vulnerability = "deny" +# The lint level for unmaintained crates +unmaintained = "warn" +# The lint level for crates that have been yanked from their source registry +yanked = "warn" +# The lint level for crates with security notices. Note that as of +# 2019-12-17 there are no security notice advisories in +# https://github.com/rustsec/advisory-db +notice = "warn" +# A list of advisory IDs to ignore. Note that ignored advisories will still +# output a note when they are encountered. +ignore = [ + #"RUSTSEC-0000-0000", +] +# Threshold for security vulnerabilities, any vulnerability with a CVSS score +# lower than the range specified will be ignored. Note that ignored advisories +# will still output a note when they are encountered. +# * None - CVSS Score 0.0 +# * Low - CVSS Score 0.1 - 3.9 +# * Medium - CVSS Score 4.0 - 6.9 +# * High - CVSS Score 7.0 - 8.9 +# * Critical - CVSS Score 9.0 - 10.0 +#severity-threshold = + +# This section is considered when running `cargo deny check licenses` +# More documentation for the licenses section can be found here: +# https://embarkstudios.github.io/cargo-deny/checks/licenses/cfg.html +[licenses] +# The lint level for crates which do not have a detectable license +unlicensed = "deny" +# List of explictly allowed licenses +# See https://spdx.org/licenses/ for list of possible licenses +# [possible values: any SPDX 3.11 short identifier (+ optional exception)]. +allow = [ + "MIT", + "Apache-2.0", + "BSD-3-Clause", + "Unicode-DFS-2016", +] +# List of explictly disallowed licenses +# See https://spdx.org/licenses/ for list of possible licenses +# [possible values: any SPDX 3.11 short identifier (+ optional exception)]. +deny = [ + #"Nokia", +] +# Lint level for licenses considered copyleft +copyleft = "warn" +# Blanket approval or denial for OSI-approved or FSF Free/Libre licenses +# * both - The license will be approved if it is both OSI-approved *AND* FSF +# * either - The license will be approved if it is either OSI-approved *OR* FSF +# * osi-only - The license will be approved if is OSI-approved *AND NOT* FSF +# * fsf-only - The license will be approved if is FSF *AND NOT* OSI-approved +# * neither - This predicate is ignored and the default lint level is used +allow-osi-fsf-free = "neither" +# Lint level used when no other predicates are matched +# 1. License isn't in the allow or deny lists +# 2. License isn't copyleft +# 3. License isn't OSI/FSF, or allow-osi-fsf-free = "neither" +default = "deny" +# The confidence threshold for detecting a license from license text. +# The higher the value, the more closely the license text must be to the +# canonical license text of a valid SPDX license file. +# [possible values: any between 0.0 and 1.0]. +confidence-threshold = 0.8 +# Allow 1 or more licenses on a per-crate basis, so that particular licenses +# aren't accepted for every possible crate as with the normal allow list +exceptions = [ + # Each entry is the crate and version constraint, and its specific allow + # list + #{ allow = ["Zlib"], name = "adler32", version = "*" }, +] + +# Some crates don't have (easily) machine readable licensing information, +# adding a clarification entry for it allows you to manually specify the +# licensing information +[[licenses.clarify]] +# The name of the crate the clarification applies to +name = "encoding_rs" +# The optional version constraint for the crate +#version = "*" +# The SPDX expression for the license requirements of the crate +expression = "(Apache-2.0 OR MIT) AND BSD-3-Clause" +# One or more files in the crate's source used as the "source of truth" for +# the license expression. If the contents match, the clarification will be used +# when running the license check, otherwise the clarification will be ignored +# and the crate will be checked normally, which may produce warnings or errors +# depending on the rest of your configuration +license-files = [ + # Each entry is a crate relative path, and the (opaque) hash of its contents + { path = "COPYRIGHT", hash = 0x39f8ad31 } +] + +[licenses.private] +# If true, ignores workspace crates that aren't published, or are only +# published to private registries +ignore = false +# One or more private registries that you might publish crates to, if a crate +# is only published to private registries, and ignore is true, the crate will +# not have its license(s) checked +registries = [ + #"https://sekretz.com/registry +] + +# This section is considered when running `cargo deny check bans`. +# More documentation about the 'bans' section can be found here: +# https://embarkstudios.github.io/cargo-deny/checks/bans/cfg.html +[bans] +# Lint level for when multiple versions of the same crate are detected +multiple-versions = "warn" +# Lint level for when a crate version requirement is `*` +wildcards = "allow" +# The graph highlighting used when creating dotgraphs for crates +# with multiple versions +# * lowest-version - The path to the lowest versioned duplicate is highlighted +# * simplest-path - The path to the version with the fewest edges is highlighted +# * all - Both lowest-version and simplest-path are used +highlight = "all" +# List of crates that are allowed. Use with care! +allow = [ + #{ name = "ansi_term", version = "=0.11.0" }, +] +# List of crates to deny +deny = [ + # Each entry the name of a crate and a version range. If version is + # not specified, all versions will be matched. + #{ name = "ansi_term", version = "=0.11.0" }, + # + # Wrapper crates can optionally be specified to allow the crate when it + # is a direct dependency of the otherwise banned crate + #{ name = "ansi_term", version = "=0.11.0", wrappers = [] }, +] +# Certain crates/versions that will be skipped when doing duplicate detection. +skip = [ + #{ name = "ansi_term", version = "=0.11.0" }, +] +# Similarly to `skip` allows you to skip certain crates during duplicate +# detection. Unlike skip, it also includes the entire tree of transitive +# dependencies starting at the specified crate, up to a certain depth, which is +# by default infinite +skip-tree = [ + #{ name = "ansi_term", version = "=0.11.0", depth = 20 }, +] + +# This section is considered when running `cargo deny check sources`. +# More documentation about the 'sources' section can be found here: +# https://embarkstudios.github.io/cargo-deny/checks/sources/cfg.html +[sources] +# Lint level for what to happen when a crate from a crate registry that is not +# in the allow list is encountered +unknown-registry = "warn" +# Lint level for what to happen when a crate from a git repository that is not +# in the allow list is encountered +unknown-git = "warn" +# List of URLs for allowed crate registries. Defaults to the crates.io index +# if not specified. If it is specified but empty, no registries are allowed. +allow-registry = ["https://github.com/rust-lang/crates.io-index"] +# List of URLs for allowed Git repositories +allow-git = [] + +[sources.allow-org] +# 1 or more github.com organizations to allow git sources for +#github = [""] +# 1 or more gitlab.com organizations to allow git sources for +#gitlab = [""] +# 1 or more bitbucket.org organizations to allow git sources for +#bitbucket = [""] diff --git a/rustfmt.toml b/rustfmt.toml new file mode 100644 index 0000000..0a9eda5 --- /dev/null +++ b/rustfmt.toml @@ -0,0 +1,8 @@ +fn_single_line = true +group_imports = "StdExternalCrate" +imports_granularity = "Crate" +overflow_delimited_expr = true +reorder_impl_items = true +use_field_init_shorthand = true +use_small_heuristics = "Max" +where_single_line = true diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..19e7e80 --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,368 @@ +use std::str::FromStr; + +fn parse_qualifiers(mut str: &str) -> (String, String, &str) { + let mut pre = String::new(); + let mut post = String::new(); + for c in str.chars() { + match c { + 'P' => post.push('*'), + 'R' => post.push('&'), + 'C' => pre.push_str("const "), + 'U' => pre.push_str("unsigned "), + 'S' => pre.push_str("signed "), + _ => break, + }; + str = &str[1..]; + } + (pre, post, str) +} + +fn parse_digits(str: &str) -> Option<(usize, &str)> { + if let Some(idx) = str.find(|c: char| !c.is_digit(10)) { + Some((usize::from_str(&str[..idx]).ok()?, &str[idx..])) + } else { + // all digits! + Some((usize::from_str(str).ok()?, "")) + } +} + +fn demange_template_args(mut str: &str) -> Option<(&str, String)> { + let qualified = if let Some(start_idx) = str.find('<') { + let end_idx = str.rfind('>')?; + let mut args = &str[start_idx + 1..end_idx]; + str = &str[..start_idx]; + let mut qualified = str.to_string(); + qualified += "<"; + while !args.is_empty() { + let (arg, rest) = demangle_arg(args)?; + qualified += arg.as_str(); + if rest.is_empty() { + break; + } else { + qualified += ", "; + } + args = &rest[1..]; + } + qualified += ">"; + qualified + } else { + str.to_string() + }; + Some((str, qualified)) +} + +fn demangle_class(str: &str) -> Option<(String, String, &str)> { + let (size, rest) = parse_digits(str)?; + // hack for template argument constants + if rest.is_empty() || rest.starts_with(",") { + let out = format!("{}", size); + return Some((out.clone(), out, rest)); + } + let (class_name, qualified) = demange_template_args(&rest[..size])?; + Some((class_name.to_string(), qualified, &rest[size..])) +} + +fn demangle_qualified_class(mut str: &str) -> Option<(String, String, &str)> { + if str.starts_with('Q') { + let count = usize::from_str(&str[1..2]).ok()?; + str = &str[2..]; + let mut last_class = String::new(); + let mut qualified = String::new(); + for i in 0..count { + let (class_name, full, rest) = demangle_class(str)?; + qualified += full.as_str(); + last_class = class_name; + str = rest; + if i < count - 1 { + qualified += "::"; + } + } + Some((last_class, qualified, str)) + } else { + return demangle_class(str); + } +} + +fn demangle_arg(mut str: &str) -> Option<(String, &str)> { + let mut result = String::new(); + let (pre, mut post, rest) = parse_qualifiers(str); + result += pre.as_str(); + str = rest; + if str.starts_with('Q') || str.starts_with(|c: char| c.is_digit(10)) { + let (_, qualified, rest) = demangle_qualified_class(str)?; + result += qualified.as_str(); + result += post.as_str(); + return Some((result, rest)); + } + let mut is_member = false; + if str.starts_with('M') { + is_member = true; + let (_, member, rest) = demangle_qualified_class(&str[1..])?; + post = format!("{}::*{}", member, post); + if !rest.starts_with("F") { + return None; + } + str = rest; + } + if is_member || str.starts_with('F') { + str = &str[1..]; + if is_member { + // Member functions always(?) include "const void*, void*" + if !str.starts_with("PCvPv") { + return None; + } + str = &str[5..]; + } + let (args, rest) = demangle_function_args(str)?; + if !rest.starts_with("_") { + return None; + } + let (ret, rest) = demangle_arg(&rest[1..])?; + result += format!("{} ({})({})", ret, post, args).as_str(); + return Some((result, rest)); + } + if str.starts_with('A') { + todo!("array") + } + result.push_str(match str.chars().next().unwrap() { + 'i' => "int", + 'b' => "bool", + 'c' => "char", + 's' => "short", + 'l' => "long", + 'x' => "long long", + 'f' => "float", + 'd' => "double", + 'w' => "wchar_t", + 'v' => "void", + 'e' => "...", + _ => return None, + }); + result += post.as_str(); + Some((result, &str[1..])) +} + +fn demangle_function_args(mut str: &str) -> Option<(String, &str)> { + let mut result = String::new(); + while !str.is_empty() { + if !result.is_empty() { + result += ", "; + } + let (arg, rest) = demangle_arg(str)?; + result += arg.as_str(); + str = rest; + if str.starts_with("_") || str.starts_with(",") { + break; + } + } + Some((result, str)) +} + +fn demangle_special_function(str: &str, class_name: &str) -> Option { + Some( + match str { + "dt" => return Some("~".to_string() + class_name), + "ct" => class_name, + "nw" => "operator new", + "nwa" => "operator new[]", + "dl" => "operator delete", + "dla" => "operator delete[]", + "pl" => "operator+", + "mi" => "operator-", + "ml" => "operator*", + "dv" => "operator/", + "md" => "operator%", + "er" => "operator^", + "ad" => "operator&", + "or" => "operator|", + "co" => "operator~", + "nt" => "operator!", + "as" => "operator=", + "lt" => "operator<", + "gt" => "operator>", + "apl" => "operator+=", + "ami" => "operator-=", + "amu" => "operator*=", + "adv" => "operator/=", + "amd" => "operator%=", + "aer" => "operator^=", + "aad" => "operator&=", + "aor" => "operator|=", + "ls" => "operator<<", + "rs" => "operator>>", + "ars" => "operator>>=", + "als" => "operator<<=", + "eq" => "operator==", + "ne" => "operator!=", + "le" => "operator<=", + "ge" => "operator>=", + "aa" => "operator&&", + "oo" => "operator||", + "pp" => "operator++", + "mm" => "operator--", + "cm" => "operator,", + "rm" => "operator->*", + "rf" => "operator->", + "cl" => "operator()", + "vc" => "operator[]", + _ => return None, + } + .to_string(), + ) +} + +pub fn demangle(mut str: &str) -> Option { + let mut special = false; + let mut cnst = false; + let mut fn_name: String; + if str.starts_with("__") { + special = true; + str = &str[2..]; + } + { + let (fn_name_out, rest) = str.split_once("__")?; + let (_, qualified) = demange_template_args(fn_name_out)?; + fn_name = qualified; + str = rest; + } + let (class_name, mut qualified, rest) = demangle_qualified_class(str)?; + str = rest; + if special { + fn_name = demangle_special_function(fn_name.as_str(), class_name.as_str())?; + } + if str.starts_with("C") { + str = &str[1..]; + cnst = true; + } + if str.starts_with("F") { + str = &str[1..]; + let (args, rest) = demangle_function_args(str)?; + fn_name = format!("{}({})", fn_name, args); + str = rest; + } + if str.starts_with("_") { + str = &str[1..]; + let (ret, rest) = demangle_arg(str)?; + qualified = format!("{} {}", ret, qualified); + str = rest; + } + if !str.is_empty() { + return None; + } + if cnst { + fn_name = format!("{} const", fn_name); + } + if !qualified.is_empty() { + return Some(format!("{}::{}", qualified, fn_name)); + } + Some(fn_name) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_demangle_class() { + assert_eq!( + demangle_class("24single_ptr<10CModelData>"), + Some(( + "single_ptr".to_string(), + "single_ptr".to_string(), + "" + )) + ) + } + + #[test] + fn test_demangle_qualified_class() { + assert_eq!( + demangle_qualified_class("6CActor"), + Some(("CActor".to_string(), "CActor".to_string(), "")) + ); + assert_eq!( + demangle_qualified_class("Q29CVector3f4EDim"), + Some(("EDim".to_string(), "CVector3f::EDim".to_string(), "")) + ); + assert_eq!( + demangle_qualified_class( + "Q24rstl66basic_string,Q24rstl17rmemory_allocator>" + ), + Some(( + "basic_string".to_string(), + "rstl::basic_string, rstl::rmemory_allocator>" + .to_string(), + "" + )) + ) + } + + #[test] + fn test_demangle_arg() { + assert_eq!(demangle_arg("v"), Some(("void".to_string(), ""))); + assert_eq!(demangle_arg("b"), Some(("bool".to_string(), ""))); + assert_eq!( + demangle_arg("RC9CVector3fUc"), + Some(("const CVector3f&".to_string(), "Uc")) + ); + assert_eq!( + demangle_arg("Q24rstl14char_traits,"), + Some(("rstl::char_traits".to_string(), ",")) + ); + assert_eq!( + demangle_arg("PFPCcPCc_v"), + Some(("void (*)(const char*, const char*)".to_string(), "")) + ) + } + + #[test] + fn test_demangle_function_args() { + assert_eq!(demangle_function_args("v"), Some(("void".to_string(), ""))); + assert_eq!(demangle_function_args("b"), Some(("bool".to_string(), ""))); + assert_eq!( + demangle_function_args("RC9CVector3fUc_x"), + Some(("const CVector3f&, unsigned char".to_string(), "_x")) + ); + } + + #[test] + fn test_demangle() { + assert_eq!(demangle("cfunction"), None); + assert_eq!( + demangle("__dt__6CActorFv"), + Some("CActor::~CActor(void)".to_string()) + ); + assert_eq!( + demangle("GetSfxHandle__6CActorCFv"), + Some("CActor::GetSfxHandle(void) const".to_string()) + ); + assert_eq!( + demangle("mNull__Q24rstl66basic_string,Q24rstl17rmemory_allocator>"), + Some("rstl::basic_string, rstl::rmemory_allocator>::mNull".to_string()) + ); + assert_eq!( + demangle("__ct__Q34rstl495red_black_tree,Q24rstl17rmemory_allocator>>,Q24rstl7less,Q24rstl17rmemory_allocator>>>,0,Q24rstl215select1st,Q24rstl17rmemory_allocator>>,Q24rstl7less,Q24rstl17rmemory_allocator>>>>,Q24rstl8less,Q24rstl17rmemory_allocator>8iteratorFPQ34rstl495red_black_tree,Q24rstl17rmemory_allocator>>,Q24rstl7less,Q24rstl17rmemory_allocator>>>,0,Q24rstl215select1st,Q24rstl17rmemory_allocator>>,Q24rstl7less,Q24rstl17rmemory_allocator>>>>,Q24rstl8less,Q24rstl17rmemory_allocator>4nodePCQ34rstl495red_black_tree,Q24rstl17rmemory_allocator>>,Q24rstl7less,Q24rstl17rmemory_allocator>>>,0,Q24rstl215select1st,Q24rstl17rmemory_allocator>>,Q24rstl7less,Q24rstl17rmemory_allocator>>>>,Q24rstl8less,Q24rstl17rmemory_allocator>6header"), + Some("rstl::red_black_tree, rstl::rmemory_allocator>>, rstl::less, rstl::rmemory_allocator>>>, 0, rstl::select1st, rstl::rmemory_allocator>>, rstl::less, rstl::rmemory_allocator>>>>, rstl::less, rstl::rmemory_allocator>::iterator::iterator(rstl::red_black_tree, rstl::rmemory_allocator>>, rstl::less, rstl::rmemory_allocator>>>, 0, rstl::select1st, rstl::rmemory_allocator>>, rstl::less, rstl::rmemory_allocator>>>>, rstl::less, rstl::rmemory_allocator>::node*, const rstl::red_black_tree, rstl::rmemory_allocator>>, rstl::less, rstl::rmemory_allocator>>>, 0, rstl::select1st, rstl::rmemory_allocator>>, rstl::less, rstl::rmemory_allocator>>>>, rstl::less, rstl::rmemory_allocator>::header*)".to_string()), + ); + assert_eq!( + demangle("for_each,l>>__3stdFPP12MultiEmitterPP12MultiEmitterQ23std51binder2nd,l>_Q23std51binder2nd,l>"), + Some("std::binder2nd, long> std::for_each, long>>(MultiEmitter**, MultiEmitter**, std::binder2nd, long>)".to_string()) + ); + assert_eq!( + demangle("__ct__Q43std3tr16detail383function_imp,Q33std3tr1228tuple,Q53std3tr112placeholders6detail5ph<2>,Q33std3tr13nat,Q33std3tr13nat,Q33std3tr13nat,Q33std3tr13nat,Q33std3tr13nat,Q33std3tr13nat,Q33std3tr13nat>>,0,1>FRCQ43std3tr16detail383function_imp,Q33std3tr1228tuple,Q53std3tr112placeholders6detail5ph<2>,Q33std3tr13nat,Q33std3tr13nat,Q33std3tr13nat,Q33std3tr13nat,Q33std3tr13nat,Q33std3tr13nat,Q33std3tr13nat>>,0,1>"), + Some("std::tr1::detail::function_imp, std::tr1::tuple, std::tr1::placeholders::detail::ph<2>, std::tr1::nat, std::tr1::nat, std::tr1::nat, std::tr1::nat, std::tr1::nat, std::tr1::nat, std::tr1::nat>>, 0, 1>::function_imp(const std::tr1::detail::function_imp, std::tr1::tuple, std::tr1::placeholders::detail::ph<2>, std::tr1::nat, std::tr1::nat, std::tr1::nat, std::tr1::nat, std::tr1::nat, std::tr1::nat, std::tr1::nat>>, 0, 1>&)".to_string()) + ); + assert_eq!( + demangle("createJointController<11IKJointCtrl>__2MRFP11IKJointCtrlPC9LiveActorUsM11IKJointCtrlFPCvPvPQ29JGeometry64TPosition3>>RC19JointControllerInfo_bM11IKJointCtrlFPCvPvPQ29JGeometry64TPosition3>>RC19JointControllerInfo_b_P15JointController"), + Some("JointController* MR::createJointController(IKJointCtrl*, const LiveActor*, unsigned short, bool (IKJointCtrl::*)(JGeometry::TPosition3>>*, const JointControllerInfo&), bool (IKJointCtrl::*)(JGeometry::TPosition3>>*, const JointControllerInfo&))".to_string()) + ); + assert_eq!( + demangle("execCommand__12JASSeqParserFP8JASTrackM12JASSeqParserFPCvPvP8JASTrackPUl_lUlPUl"), + Some("JASSeqParser::execCommand(JASTrack*, long (JASSeqParser::*)(JASTrack*, unsigned long*), unsigned long, unsigned long*)".to_string()) + ); + assert_eq!( + demangle("AddWidgetFnMap__10CGuiWidgetFiM10CGuiWidgetFPCvPvP15CGuiFunctionDefP18CGuiControllerInfo_i"), + Some("CGuiWidget::AddWidgetFnMap(int, int (CGuiWidget::*)(CGuiFunctionDef*, CGuiControllerInfo*))".to_string()) + ); + } +} diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..75b7180 --- /dev/null +++ b/src/main.rs @@ -0,0 +1,21 @@ +use argh::FromArgs; + +mod lib; + +#[derive(FromArgs)] +/// CodeWarrior C++ demangler +struct Args { + /// the symbol to demangle + #[argh(positional)] + symbol: String, +} + +fn main() -> Result<(), &'static str> { + let args: Args = argh::from_env(); + return if let Some(symbol) = lib::demangle(args.symbol.as_str()) { + println!("{}", symbol); + Ok(()) + } else { + Err("Failed to demangle symbol") + }; +}