dfinity / dfinity/candid

Add a proc-macro for a string principal constant

Open
#691 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

enhancement
Dominant language
Rust
Stars
301
Forks
85
Avg merge
1h 4m
Merged PRs (30d)
4

Description

Is your feature request related to a problem? Please describe.
Principal::from_text is not const but there's many circumstances in which a principal constant is wanted in code. Principal::from_slice is const but it is much harder to inspect and verify as it just takes a byte slice

Describe the solution you'd like

principal!("...")

Describe alternatives you've considered

Principal::from_slice(&[...]), but as mentioned above, that is less than ideal.

Potential implementation

use candid::Principal;
use proc_macro::TokenStream;
use quote::{quote, ToTokens};
use syn::{parse_macro_input, LitStr, parse::Parse, parse::ParseStream};

struct CandidPrincipal(Principal);

impl Parse for CandidPrincipal {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let text = input.parse::<LitStr>()?.value();
        Principal::from_text(&text)
            .map(Self)
            .map_err(|e| syn::Error::new(input.span(), e.to_string()))
    }
}

impl ToTokens for CandidPrincipal {
    fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
        let bytes = self.0.as_slice();
        tokens.extend(quote! {
            ::candid::Principal::from_slice(&[#(#bytes),*])
        })
    }
}

#[proc_macro]
pub fn principal(tokens: TokenStream) -> TokenStream {
    parse_macro_input!(tokens as CandidPrincipal)
        .into_token_stream()
        .into()
}

syn and quote are dependencies of ic-cdk anyway so this will not have any negative effects on compilation performance

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by locating the Rust crate that exposes Principal and the existing proc-macro entry points, then review Principal::from_text and Principal::from_slice. Compare the proposed principal! implementation with the project's syn and quote dependencies. Done means a string principal can be validated and expanded into a const-compatible Principal value.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
tooling
Issue type
Feature
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.