D exemplary language parsing.

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/fqbqrr/article/details/99204716

code show as below:

import dparse.ast;
import std.stdio, std.range;

class TestVisitor : ASTVisitor
{
    alias visit = ASTVisitor.visit;
    int indentLevel;

    override void visit(const FunctionDeclaration decl)
    {
        writeln(' '.repeat(indentLevel * 4), decl.name.text);
        indentLevel++;
        scope (exit) indentLevel--;
        decl.accept(this);
    }
}

void main()
{
    import dparse.lexer;
    import dparse.parser : parseModule;
    import dparse.rollback_allocator : RollbackAllocator;

    auto sourceCode = q{
        void foo() @safe {
            void bar();
        }
    };
    LexerConfig config;
    auto cache = StringCache(StringCache.defaultBucketCount);
    auto tokens = getTokensForParser(sourceCode, config, &cache);

    RollbackAllocator rba;
    auto m = parseModule(tokens, "test.d", &rba);
    auto visitor = new TestVisitor();
    visitor.visit(m);
}

dub a single configuration file dub.sdl:

name "li"
dependency "libdparse" version="~>0.7"
sourceFiles "li.d"
targetType "executable"

Guess you like

Origin blog.csdn.net/fqbqrr/article/details/99204716