Skip to content

Mapping between R string constants and C enum values #1961

Open

Description

@szhorvat

There are many igraph functions that take enum constants, e.g. to choose a method or mode of operation to use.

The mapping from R to these values happens in:

https://github.com/igraph/rigraph/blob/main/tools/stimulus/types-RR.yaml

However, the R interface produces raw integers, and does not use the enum constant names in C. Here's an example:

%I% <- switch(igraph.match.arg(%I%), "cartesian"=0L, "lexicographic"=1L, "strong"=2L, "tensor"=3L)

Notice the values 0, 1, 2, 3 instead of the C constants IGRAPH_PRODUCT_CARTESIAN, IGRAPH_PRODUCT_LEXICOGRAPHIC, etc.

This situation is not ideal and somewhat dangerous. If we change the list of enum values in C, we do not technically break API (only ABI), but the raw integer encoding does change. This will break the R interface.

Luckily, this happens rarely, but there's a higher risk while working in C/igraph 1.0. It happened twice recently, namely:

Unfortunately I did not immediately realize that doing this breaks R. We'll have to review which enum values, if any, changed between 0.10 and 1.0. It may be only the single one in igraph_es_type_t. I'll try to do this and document such changes in the changelog, to make sure that you can pick it up on the R side. We'll also try to avoid such changes as much as possible.

But, if you have ideas on how to do it, it'd be best if we could find a solution to use the C enum names directly, and reduce the risk of breakage.

In the Mathematica interface I use a two-level solution:

  • In Mathematica code, I translate strings to intermediate integers.
  • Then in C code, I translate these intermediate integers to actual enum constant names.

This way the interface is robust to re-numbering the constants in C. Admittedly, this is a bit more work, but not by much, and can probably be done through types-RR.yaml (translates R strings to integers) and types-RC.yaml (translates intermediate integers to constant names).

CC @krlmlr

Activity

  1. krlmlr commented on Jul 7, 2025

    @krlmlr
    Contributor

    How do you feel about keeping front-facing enum values stable for eternity?

  2. szhorvat commented on Jul 7, 2025

    @szhorvat
    MemberAuthor

    It's doable, but I'm not too happy about it. It increases the mental load when working with this: Yet another thing to keep in mind and pay attention to when reviewing PRs.

    Here's an example where it's getting ugly. I really hate seeing this:

    https://github.com/igraph/igraph/blob/009eb2f83d764af55acb01a6691d608abcf99a10/include/igraph_error.h#L274-L321

    This one has to be kept in sync with an array of strings which got a lot of NULL values as a result of the removed codes.

    At least for 1.0, I'm hoping to have a "clean start" and drop as much historical baggage as possible, instead of accumulating more.

    On the other hand, the values MUST stay stable within a major release series (can't change between 1.x releases) to ensure ABI compatibility.

    Ping @ntamas as well for input.

  3. szhorvat commented on Jul 7, 2025

    @szhorvat
    MemberAuthor

    Is this an issue for you in MATLAB-igraph, @DavidRConnell ?

    What about in Julia, @Krastanov?

  4. Krastanov commented on Jul 7, 2025

    @Krastanov

    On the julia side this is not a worry, all C enums are available by name, no need for remapping or using strings, e.g.:

    julia> using IGraphs, Graphs
    
    julia> LibIGraph.radius(IGraph(random_regular_graph(10,5)), LibIGraph.IGRAPH_ALL)
    (2.0,)
    
    julia> LibIGraph.IGRAPH_ES_ALL_BETWEEN
    IGRAPH_ES_ALL_BETWEEN::igraph_es_type_t = 0x0000000c

    A bit verbose because we do not export any of the symbols by default.

  5. krlmlr commented on Jul 7, 2025

    @krlmlr
    Contributor

    For R, we might be able to save a bit of boilerplate by translating the C code that declares the enums into R. Do all constants fit into a global namespace, or are collisions to be expected?

  6. szhorvat commented on Jul 7, 2025

    @szhorvat
    MemberAuthor

    Do all constants fit into a global namespace, or are collisions to be expected?

    Do you mean the enum constant names in C? They must fit, as they share a namespace. Usually there's a prefix, as in IGRAPH_PREFIX_SOMETHING.

  7. DavidRConnell commented on Jul 7, 2025

    @DavidRConnell

    Thanks for the warning. I try to avoid knowing the integer values of enums by using C-side arrays to map between enums and MATLAB-side strings with position defined by the enums. Like:

    char const* methods[] = {
      [IGRAPH_COMMCMP_VI] = "vi",
      [IGRAPH_COMMCMP_NMI] = "nmi",
      [IGRAPH_COMMCMP_RAND] = "rand",
      [IGRAPH_COMMCMP_SPLIT_JOIN] = "split_join",
      [IGRAPH_COMMCMP_ADJUSTED_RAND] = "adjusted_rand"
    };

    Then iterate over the array until I find a matching string:

    /* Generic string selector.
       Find which of a predefined set of strings an input value matches.
       Returns the index, which should correspond to an enum that can be used in a
       switch statement.
    
       If no match found, returns -1. */
    igraph_integer_t mxIgraphSelectMethod(
      mxArray const* p, char const* methods[], igraph_integer_t const n_methods)
    {
      if (!mxIsChar(p)) {
        mxIgraphSetError(IGRAPH_EINVAL);
        mxIgraphSetErrorMsg("Method name must be specified as a string.");
        return -1;
      }
    
      char* name = mxArrayToString(p);
      for (igraph_integer_t i = 0; i < n_methods; i++) {
        if (methods[i] && strcmp(name, methods[i]) == 0) {
          return i;
        }
      }
    
      mxIgraphSetError(IGRAPH_EINVAL);
      mxIgraphSetErrorMsg("Received unexpected method name \"%s\".", name);
      return -1;
    }

    There are a few places where I do depend on knowing the values though, namely the neighbor mode enum that starts at 1 instead of 0.

    // Select a neighbor mode.
    igraph_neimode_t mxIgraphModeFromOptions(mxArray const* p)
    {
      igraph_neimode_t res;
      igraph_integer_t n_modes = 3;
      // Mode enum starts at 1 not 0.
      char const* modes[] = {
        [IGRAPH_OUT - 1] = "out", [IGRAPH_IN - 1] = "in", [IGRAPH_ALL - 1] = "all"
      };
    
      res = mxIgraphSelectMethod(mxGetField(p, 0, "mode"), modes, n_modes);
    
      if (res == -1) {
        mxIgraphSetError(IGRAPH_EINVMODE);
        mxIgraphSetErrorMsg(
          "Received invalid mode name \"%s\".", mxGetField(p, 0, "mode"));
      }
    
      return res + 1;
    }

    But I think I could rewrite this to not subtract out the minimum value and leave modes[0] to its implicit value. Not sure if there's a dynamic way to determine the number of enum values though so I don't have to hardcode it into n_modes. In my internal enums I extra value at the end of the list to use for n.

    enum {
      MXIGRAPH_CENTRALITY_CLOSENESS = 0,
      MXIGRAPH_CENTRALITY_HARMONIC,
      MXIGRAPH_CENTRALITY_BETWEENNESS,
      MXIGRAPH_CENTRALITY_PAGERANK,
      MXIGRAPH_CENTRALITY_BURT,
      MXIGRAPH_CENTRALITY_EIGENVECTOR,
      MXIGRAPH_CENTRALITY_N
    };
    
    char const* methods[MXIGRAPH_CENTRALITY_N] = {
      [MXIGRAPH_CENTRALITY_CLOSENESS] = "closeness",
      [MXIGRAPH_CENTRALITY_HARMONIC] = "harmonic",
      [MXIGRAPH_CENTRALITY_BETWEENNESS] = "betweenness",
      [MXIGRAPH_CENTRALITY_PAGERANK] = "pagerank",
      [MXIGRAPH_CENTRALITY_BURT] = "burt",
      [MXIGRAPH_CENTRALITY_EIGENVECTOR] = "eigenvector"
    };
    
    igraph_integer_t method =
      mxIgraphSelectMethod(prhs[1], methods, MXIGRAPH_CENTRALITY_N);
    MXIGRAPH_CHECK_METHOD(method, prhs[1]);

    I don't know if that pattern would be useful to anyone else or if adding it in to igraph enums would break anything, but I find it convenient as the only order we have to assume is the N value will be the final member of the enum, if values are added in later the C compiler will handle all the changes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions