In which structure you can save the Abstract syntax tree for the PHP language . I am writing code generators, but somehow using simple things like file fillers, collecting methods by cantating the lines, different cycles on the base, etc. I went through a different bunch of options for storing information on a project, but I would like to come up with a more correct approach. But how to do this is not clear. I found out that there is such a thing as an abstract syntax tree , and I want to ask the people, can anyone come across a solution for .NET?

Please do not minus and close the question, delete the question after a week myself.

    1 answer 1

    See, for an abstract syntax tree, it's most obvious to use a data structure like a tree. ( Thank you, cap! )

    There is no built-in tree in C #, but it is easy to program it yourself. What operations do you need? For example, getting all child elements, as well as traversing (implementation of the Visitor pattern).

    We try!

    class TreeNode { public List<TreeNode> Children { get; } = new List<TreeNode>(); class TreeNode(IEnumerable<TreeNode> children = null) { if (children != null) Children.AddRange(children); } public abstract Accept(ITreeNodeVisitor visitor); } interface ITreeNodeVisitor { void Visit(TreeNode n); void Visit(FunctionNode cn); void Visit(AssignmentNode an); // и т. д. } 

    With this, you can implement specific types of nodes:

     class AdditionNode : TreeNode { public AdditionNode(TreeNode left, TreeNode right) : base(new[] { left, right }) { } public override Accept(ITreeNodeVisitor visitor) => visitor.Visit(this); } 

    etc.

    So, you will have a top level node, which will have internal nodes and recursively down the rest of the tree.

    (If you want your nodes to be immutable, you should probably set List<TreeNode> instead of a IReadOnlyList<TreeNode> .)

    • and all sorts of Expression will not work here? - Grundy
    • @Grundy: I ​​don’t like them: (1) they are sharpened for C # constructions, not PHP, and (2) you cannot control the design: the decision “immutable or not” has already been made by someone for you. Although yes, there would be an option or at least a source of inspiration. - VladD