r/ProgrammingLanguages • • Oct 27 '26

Resolving relationships between elements

For my programming programming language Bits Runner Code I am thinking of implementing automatic resolving in what order structs, interfaces, etc should be defined and declared so they can interact with each other. It should be possible to embed structs within each other, but at the same time there cannot be a circular reference. How something like this could be implemented or maybe it is not the best idea?

BRC doesn't have header files, so right now source files and definitions within them have to be listed in a specific order. I would like it to be quite explicit but also hassle free.

6 Upvotes

15 comments sorted by

View all comments

2

u/AustinVelonaut Admiran Oct 27 '26 edited Oct 27 '26

You can initally parse the definitions, simply keeping name references to other definitions used in them, then build a dependency graph with each definition name as a key and each definition name they use as values, then use a Strongly-Connected Components algorithm like Kosaraju or Tarjan to determine the correct order for the definitions, and if any circular-references (non-singleton components) exist.

1

u/marshaharsha Nov 01 '26

What does strongly connected components tell you that (simpler) detection of a directed cycle does not? If there is no directed cycle, then topological sorting gives you an ordering. 

2

u/AustinVelonaut Admiran Nov 01 '26 edited Nov 01 '26

It gives you both at the same time (and reports all of the components in any cycles, which I use for reporting the cyclic-dependency error). I don't think cycle-detection + topological sorting is much simpler; my implementation of findSCCs is just 22 lines. Also, I need to group mutually-recursive definitions together, separate from regular or self-recursive definitions, so it is a natural algorithm to use.