File: tree.hh

package info (click to toggle)
faust 2.79.3%2Bds-2
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 397,496 kB
  • sloc: cpp: 278,433; ansic: 116,164; javascript: 18,529; vhdl: 14,052; sh: 13,884; java: 5,900; objc: 3,852; python: 3,222; makefile: 2,655; cs: 1,672; lisp: 1,146; ruby: 954; yacc: 586; xml: 471; lex: 247; awk: 110; tcl: 26
file content (354 lines) | stat: -rw-r--r-- 12,940 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
/************************************************************************
 ************************************************************************
    FAUST compiler
    Copyright (C) 2003-2024 GRAME, Centre National de Creation Musicale
    ---------------------------------------------------------------------
    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published by
    the Free Software Foundation; either version 2.1 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 ************************************************************************
 ************************************************************************/

/*****************************************************************************
******************************************************************************/

/** \file tree.hh
 * A tree library with hashconsing and maximal sharing capabilities.
 *
 * <b>API:</b>
 *
 * \li tree (n)            : tree of node n with no branch
 * \li tree (n, t1)        : tree of node n with a branch t
 * \li tree (n, t1,...,tm) : tree of node n with m branches t1,...,tm
 *
 * <b>Useful conversions :</b>
 *
 * \li int         tree2int (t)    : if t has a node of type int, return it otherwise error
 * \li float       tree2double (t) : if t has a node of type double, return it otherwise error
 * \li const char  tree2str (t)    : if t has a node of type symbol, return its name otherwise error
 * \li void        tree2ptr (t)    : if t has a node of type ptr, return it otherwise error
 *
 * <b>Pattern matching :</b>
 *
 * \li if (isTree (t, n))           : t has node n and no branches;
 * \li if (isTree (t, n, &t1)       : t has node n and 1 branch, t1 is set accordingly;
 * \li if (isTree (t, n, &t1...&tm) : t has node n and m branches, ti's are set accordingly;
 *
 * <b>Accessors :</b>
 *
 * \li t->node()     : the node of t { return fNode; }
 * \li t->height()   : lambda height such that H(x)=0, H(\x.e)=1+H(e), H(e*f)=max(H(e),H(f))
 * \li t->arity()    : the number of branches of t { return fArity; }
 * \li t->branch(i)  : the ith branch of t
 *
 * <b>Attributs :</b>
 *
 * \li t->attribut()   : return the attribute (also a tree) of t
 * \li t->attribut(t') : set the attribute of t to t'
 *
 * <b>Properties:</b>
 *
 * If p and q are two CTree pointers :
 *     p != q <=> *p != *q
 *
 **/

/*****************************************************************************
******************************************************************************/

#ifndef __TREE__
#define __TREE__

#include <map>
#include <vector>

#include "exception.hh"
#include "garbageable.hh"
#include "node.hh"
#include "symbol.hh"

//---------------------------------API---------------------------------------

class CTree;
typedef CTree* Tree;

typedef std::vector<Tree> tvec;

namespace std {

// The std::less <CTree*>comparison function is redefined to provide an unique and stable ordering
// for all CTree instances and so maintain determinism.
template <>
struct less<CTree*> {
    bool operator()(const CTree* lhs, const CTree* rhs) const;
};

}  // namespace std

/**
 * A CTree = (Node x [CTree]) is the association of a content Node and a list of subtrees
 * called branches. In order to maximize the sharing of trees, hashconsing techniques are used.
 * Ctrees at different addresses always have a different content. A first consequence of this
 * approach is that a fast equality test on pointers can be used as an equality test on CTrees.
 * A second consequence is that a CTree can NEVER be modified. But a property list is associated
 * to each CTree that can be used to attach arbitrary information to it. Due to the maximal
 * sharing property it is therefore easy to do memoization using these property lists.
 *
 * Means are also provided to do maximal sharing on recursive trees. The idea is to start from
 * a deBruijn representation and progressively build a classical representation such that
 * alpha-equivalent recursive CTrees are necessarily identical (and therefore shared).
 *
 **/

class LIBFAUST_API CTree : public virtual Garbageable {
   protected:
    static const int kHashTableSize = 400009;     ///< size of the hash table (prime number)
    static size_t    gSerialCounter;              ///< the serial number counter
    static Tree      gHashTable[kHashTableSize];  ///< hash table used for "hash consing"

   public:
    static bool gDetails;  ///< CTree::print() print with more details when true
    ///< Should be incremented for each new visit to keep track of visited tree
    static unsigned int gVisitTime;

    typedef std::map<Tree, Tree> plist;

   protected:
    // fields
    Tree         fNext;        ///< next tree in the same hashtable entry
    Node         fNode;        ///< the node content of the tree
    void*        fType;        ///< the type of a tree
    plist        fProperties;  ///< the properties list attached to the tree
    size_t       fHashKey;     ///< the hashtable key
    size_t       fSerial;      ///< the increasing serial number
    int          fAperture;    ///< how "open" is a tree (synthesized field)
    unsigned int fVisitTime;   ///< keep track of visits
    tvec         fBranch;      ///< the subtrees

    CTree() : fNext(nullptr), fType(nullptr), fHashKey(0), fSerial(0), fAperture(0), fVisitTime(0)
    {
    }
    ///< construction is private, uses tree::make instead
    CTree(size_t hk, const Node& n, const tvec& br);

    ///< used to check if an equivalent tree already exists
    bool equiv(const Node& n, const tvec& br) const;

    static size_t calcTreeHash(
        const Node& n,
        const tvec& br);  ///< compute the hash key of a tree according to its node and branches
    static int calcTreeAperture(const Node& n, const tvec& br);  ///< compute how open is a tree

   public:
    virtual ~CTree();

    static Tree make(const Node& n, int ar,
                     Tree br[]);  ///< return a new tree or an existing equivalent one
    static Tree make(const Node& n,
                     const tvec& br);  ///< return a new tree or an existing equivalent one

    // Accessors
    const Node& node() const { return fNode; }  ///< return the content of the tree
    int         arity() const
    {
        return (int)fBranch.size();
    }  ///< return the number of branches (subtrees) of a tree
    Tree branch(int i) const { return fBranch[i]; }   ///< return the ith branch (subtree) of a tree
    const tvec& branches() const { return fBranch; }  ///< return all branches (subtrees) of a tree
    size_t      hashkey() const { return fHashKey; }  ///< return the hashkey of the tree
    size_t      serial() const { return fSerial; }    ///< return the serial of the tree
    int         aperture() const
    {
        return fAperture;
    }  ///< return how "open" is a tree in terms of free variables
    void setAperture(int a) { fAperture = a; }  ///< modify the aperture of a tree

    // Print a tree and the hash table (for debugging purposes)
    std::ostream& print(
        std::ostream& fout) const;  ///< print recursively the content of a tree on a stream
    static void control();          ///< print the hash table content (for debug purpose)

    static void init();

    // type information
    void  setType(void* t) { fType = t; }
    void* getType() { return fType; }

    // Keep track of visited trees (WARNING : non reentrant)
    static void startNewVisit() { ++gVisitTime; }
    bool        isAlreadyVisited() { return fVisitTime == gVisitTime; }
    void        setVisited() { fVisitTime = gVisitTime; }

    // Property list of a tree
    void setProperty(Tree key, Tree value) { fProperties[key] = value; }
    void clearProperty(Tree key) { fProperties.erase(key); }
    void clearProperties() { fProperties = plist(); }

    void exportProperties(std::vector<Tree>& keys, std::vector<Tree>& values);

    Tree getProperty(Tree key)
    {
        plist::iterator i = fProperties.find(key);
        return (i == fProperties.end()) ? nullptr : i->second;
    }
};

// The comparison function relies on lhs->serial() which provides an unique and stable ordering
// for all CTree instances and so maintain determinism.
namespace std {
inline bool less<CTree*>::operator()(const CTree* lhs, const CTree* rhs) const
{
    return lhs->serial() < rhs->serial();
}
};  // namespace std

//---------------------------------API---------------------------------------
// To build trees

inline Tree tree(const Node& n)
{
    return CTree::make(n, 0, nullptr);
}

inline Tree tree(const Node& n, const Tree& a)
{
    return CTree::make(n, {a});
}

inline Tree tree(const Node& n, const Tree& a, const Tree& b)
{
    return CTree::make(n, {a, b});
}

inline Tree tree(const Node& n, const Tree& a, const Tree& b, const Tree& c)
{
    return CTree::make(n, {a, b, c});
}

inline Tree tree(const Node& n, const Tree& a, const Tree& b, const Tree& c, const Tree& d)
{
    return CTree::make(n, {a, b, c, d});
}

inline Tree tree(const Node& n, const Tree& a, const Tree& b, const Tree& c, const Tree& d,
                 const Tree& e)
{
    return CTree::make(n, {a, b, c, d, e});
}

inline Tree tree(const Node& n, const tvec& br)
{
    return CTree::make(n, br);
}

// Useful conversions
LIBFAUST_API int    tree2int(Tree t);  ///< if t has a node of type int, return it otherwise error
LIBFAUST_API double tree2double(
    Tree t);  ///< if t has a node of type double, return it otherwise error
LIBFAUST_API const char* tree2str(
    Tree t);  ///< if t has a node of type symbol, return its name otherwise error
std::string        tree2quotedstr(Tree t);
void*              tree2ptr(Tree t);  ///< if t has a node of type ptr, return it otherwise error
LIBFAUST_API void* getUserData(
    Tree t);  ///< if t has a node of type symbol, return the associated user data

// Pattern matching
bool isTree(const Tree& t, const Node& n);
bool isTree(const Tree& t, const Node& n, Tree& a);
bool isTree(const Tree& t, const Node& n, Tree& a, Tree& b);
bool isTree(const Tree& t, const Node& n, Tree& a, Tree& b, Tree& c);
bool isTree(const Tree& t, const Node& n, Tree& a, Tree& b, Tree& c, Tree& d);
bool isTree(const Tree& t, const Node& n, Tree& a, Tree& b, Tree& c, Tree& d, Tree& e);

// Printing
inline std::ostream& operator<<(std::ostream& s, const CTree& t)
{
    return t.print(s);
}

//-----------------------------------------------------------------------------
// Recursive trees
//-----------------------------------------------------------------------------

// Creation of recursive trees

Tree rec(Tree body);           ///< create a de Bruijn recursive tree
Tree rec(Tree id, Tree body);  ///< create a symbolic recursive tree

bool              isRec(Tree t, Tree& body);            ///< is t a de Bruijn recursive tree
LIBFAUST_API bool isRec(Tree t, Tree& id, Tree& body);  ///< is t a symbolic recursive tree

// Creation of recursive references

Tree ref(int level);  ///< create a de Bruijn recursive reference
Tree ref(Tree id);    ///< create a symbolic recursive reference

bool isRef(Tree t, int& level);  ///< is t a de Bruijn recursive reference
bool isRef(Tree t, Tree& id);    ///< is t a symbolic recursive reference

// Open vs Closed regarding de Bruijn references

inline bool isOpen(Tree t)
{
    return t->aperture() > 0;
}  ///< t contains free de Bruijn references

inline bool isClosed(Tree t)
{
    return t->aperture() <= 0;
}  ///< t does not contain free de Bruijn ref

// Lift by 1 the free de Bruijn references

Tree lift(Tree t);  ////< add 1 to the free de bruijn references of t

Tree deBruijn2Sym(Tree t);  ////< transform a tree from deBruijn to symbolic representation

//---------------------------------------------------------------------------

class Tabber {
    int fIndent;
    int fPostInc;

   public:
    Tabber(int n = 0) : fIndent(n), fPostInc(0) {}
    Tabber& operator++()
    {
        fPostInc++;
        return *this;
    }
    Tabber& operator--()
    {
        faustassert(fIndent > 0);
        fIndent--;
        return *this;
    }

    std::ostream& print(std::ostream& fout)
    {
        for (int i = 0; i < fIndent; i++) {
            fout << '\t';
        }
        fIndent += fPostInc;
        fPostInc = 0;
        return fout;
    }
};

// Printing
inline std::ostream& operator<<(std::ostream& s, Tabber& t)
{
    return t.print(s);
}

#endif