Scala:在运行时展开宏

时间:2018-02-04 06:11:20

标签: scala macros runtime abstract-syntax-tree

在运行时扩展宏之后,如何为scala代码获取AST?

#include <fstream>
#include <iostream>
#include <string>
using namespace std;

struct Node {
    string data;
    Node *next;
};

typedef Node *NodePtr;

NodePtr &readFile(NodePtr &, string); //function inputs the list
void printList(NodePtr &); // function to print it out
void splitMerge(NodePtr &, NodePtr &);          // fix
void merge(); //ignore this
void traverse(); //ignore this

int main() {
    ifstream fileIn("input.txt");

    string data;
    NodePtr head = NULL;
    NodePtr list2 = NULL;                       // fix

    while (fileIn >> data)
        readFile(head, data);                   // simplify
    cout << "Singly linked list: " << endl;
    printList(head);    
    cout << endl;

    splitMerge(head, list2);
    cout << "First list:" << endl;              // show both lists
    printList(head);
    cout << endl;
    cout << "Second list:" << endl;
    printList(list2);

    fileIn.close();
    return 0;
}

NodePtr &readFile(NodePtr &head,string data)
{
    NodePtr Alpha = new Node(); //new node called "Alpha
    Alpha->data = data; //assign alpha data to passed in "data"
    Alpha->next = NULL;
    NodePtr p = head; //head node

        if (p == NULL) head = Alpha; //if p is null, head is assigned alpha.
        else
        {
            while (p->next != NULL) p = p->next; //Fill nodes
            p->next = Alpha;
        }
    return head;
}

void printList(NodePtr &head)
{
    NodePtr p = head;

        while (p != NULL) //step through nodes till reaches NULL (end).
        {
            cout << p->data;
            p = p->next;
            cout << endl;
        }
}

void splitMerge(NodePtr &head, NodePtr &list2)  // fix
{
    NodePtr slow = head;
    NodePtr fast = head;
    if(head == NULL || head->next == NULL)      // simplify
        return;                                 // simplify

    while (fast->next->next != NULL)            // fix
    {
        fast = fast->next->next;
        slow = slow->next;
    }
    list2 = slow->next;                         // fix
    slow->next = NULL;                          // fix
}

谢谢!

1 个答案:

答案 0 :(得分:0)

在挖掘之后,我还没有找到一种方法来使用当前的实验反射和编译器API文档在运行时获得宏后扩展的AST,但我可以使用编译器选项-Ymacro-debug-lite打印出每个宏,因为它在编译时扩展。另外,有scalamacros.org和scalameta.org提出了下一代AST检查/操作和宏。