File: cfdg.cpp

package info (click to toggle)
contextfree 3.4%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 3,260 kB
  • sloc: cpp: 37,992; lex: 414; makefile: 123; sh: 43; python: 34
file content (351 lines) | stat: -rw-r--r-- 9,704 bytes parent folder | download
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
/*
 *

 Context Free Design Grammar - version 0.2

 Copyright (C) 2005 Chris Coyne - ccoyne77@gmail.com
 Copyright (C) 2005-2008 Mark Lentczner - markl@glyphic.com
 Copyright (C) 2005-2013 John Horigan - john@glyphic.com

 [Send me anything cool you make with it or of it.]

 This program is free software; you can redistribute it and/or
 modify it under the terms of the GNU General Public License as published
 by the Free Software Foundation; either version 2 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 General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program; if not, write to the Free Software
 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
 02111-1307  USA

 *
 */


#include "cfdg.h"

#include <string>
#include <cstring>

#include "builder.h"
#include "cfdgimpl.h"
#include <cmath>
#include "astexpression.h"
#include "scanner.h"
#include "cfdg.tab.hpp"
#include <limits>
#include "tiledCanvas.h"
#include <fstream>
#include <sstream>
#include <algorithm>
#include <streambuf>
#include <istream>


yy::location CfdgError::Default;
double Renderer::Infinity = std::numeric_limits<double>::infinity();      // Ignore the gcc warning
bool Renderer::AbortEverything = false;
unsigned Renderer::ParamCount = 0;
const CfgArray<std::string> CFDG::ParamNames = {
    "CF::AllowOverlap",
    "CF::Alpha",
    "CF::Background",
    "CF::BorderDynamic",
    "CF::BorderFixed",
    "CF::Color",
    "CF::ColorDepth",
    "CF::Frame",
    "CF::FrameTime",
    "CF::Impure",
    "CF::MaxNatural",
    "CF::MaxShapes",
    "CF::MinimumSize",
    "CF::Size",
    "CF::StartShape",
    "CF::Symmetry",
    "CF::Tile",
    "CF::Time"
};

CFG
CFDG::lookupCfg(const std::string& name)
{
    auto nameIt = std::find(ParamNames.begin(), ParamNames.end(), name);
    if (nameIt == ParamNames.end())
        return CFG::Unknown;
    
    return static_cast<CFG>(nameIt - ParamNames.begin());
}

const std::string&
CFDG::getCfgName(int c)
{
    static const std::string unknown = "unknown configuration variable";
    if (c >= 0 && c < static_cast<int>(CFG::_NumberOf))
        return ParamNames[c];
    return unknown;
}

static CFDGImpl* LatestCFDGimpl = nullptr;

std::string
CFDG::ShapeToString(int shape)
{
    if (LatestCFDGimpl)
        return LatestCFDGimpl->decodeShapeName(shape);
    else
        return "unknown";
}

const AST::ASTparameters*
CFDG::ShapeToParams(int shape)
{
    if (LatestCFDGimpl)
        return LatestCFDGimpl->getShapeParams(shape);
    else
        return nullptr;
}

CfdgError::CfdgError(const yy::location& loc, const char* msg)
: where(loc), mMsg(msg)
{
    where.begin.column -= Default.begin.column;
    where.end.column -= Default.end.column;
}

CfdgError::CfdgError(const char* msg)
: where(Default), mMsg(msg)
{
    where.begin.column = 0;
    where.end.column = 0;
}

const char*
CfdgError::what() const noexcept
{
    return mMsg;
}

const char*
DeferUntilRuntime::what() const noexcept
{
    return "Compile time action should be deferred to run time.";
}

void
CfdgError::Error(const yy::location& errLoc, const char* msg, Builder* b)
{
    if (b) {
        b->error(errLoc, msg);
        return;
    }
    
    std::lock_guard<std::recursive_mutex> lock(Builder::BuilderMutex);
    
    if (Builder::CurrentBuilder && Builder::CurrentBuilder->isMyBuilder())
        Builder::CurrentBuilder->error(errLoc, msg);
    else
        throw CfdgError(errLoc, msg);
}

void
CfdgError::Warning(const yy::location& errLoc, const char* msg)
{
    std::lock_guard<std::recursive_mutex> lock(Builder::BuilderMutex);
    
    if (Builder::CurrentBuilder && Builder::CurrentBuilder->isMyBuilder())
        Builder::CurrentBuilder->warning(errLoc, msg);
}

const std::array<const AbstractSystem::FileChar*, AbstractSystem::NumberofTempTypes> AbstractSystem::TempPrefixes = {
    FileStr("cfdg-temp-fin-"),
    FileStr("cfdg-temp-unfin-"),
    FileStr("cfdg-temp-mrg-"),
    FileStr("cfdg-temp-movie-")
};
const std::array<const AbstractSystem::FileChar*, AbstractSystem::NumberofTempTypes> AbstractSystem::TempSuffixes = {
    FileStr(""), FileStr(""), FileStr(""), FileStr(".mov")
};
const AbstractSystem::FileChar* AbstractSystem::TempPrefixAll = FileStr("cfdg-temp-");

AbstractSystem::~AbstractSystem() = default;

void AbstractSystem::stats(const Stats&)
    { }

AbstractSystem::istr_ptr
AbstractSystem::tempFileForRead(const FileString& path)
{
    return std::make_unique<std::ifstream>(path.c_str(), std::ios::binary);
}

struct membuf : std::streambuf {
    membuf(char const* base, std::size_t size) {
        char* p(const_cast<char*>(base));
        this->setg(p, p, p + size);
    }
};
struct imemstream : virtual membuf, std::istream {
    imemstream(char const* base, std::size_t size)
        : membuf(base, size)
        , std::istream(static_cast<std::streambuf*>(this)) {
    }
};

AbstractSystem::istr_ptr
AbstractSystem::openFileForRead(const std::string& path)
{
    if (!mFirstCfdgRead) {
        char dirchar =
#ifdef _WIN32
            '\\';
#else
            '/';
#endif
        auto dirloc = path.rfind(dirchar);
        auto exfile = path.substr(dirloc == std::string::npos ? 0 : dirloc + 1);

        auto example = ExamplesMap.find(exfile);
        if (example != ExamplesMap.end()) {
            auto [v3cfdg, v2cfdg] = example->second;
            auto cfdg = cfdgVersion == 2 ? v2cfdg : v3cfdg;
            return std::make_unique<imemstream>(cfdg, std::strlen(cfdg));
        }
    } else {
        mFirstCfdgRead = false;
    }

    istr_ptr f = std::make_unique<std::ifstream>(path.c_str(), std::ios::binary);
    if (f && !f->good())
        f.reset();

    return f;
}

Canvas::~Canvas() = default;

Renderer::Renderer(int w, int h)
: requestStop(false),
  requestFinishUp(false),
  requestUpdate(false),
  m_width(w), m_height(h)
{ }

Renderer::~Renderer() = default;



CFDG::~CFDG() = default;


cfdg_ptr
CFDG::ParseFile(const char* fname, AbstractSystem* system, int variation,
                std::string defs)
{
    cfdgi_ptr pCfdg;
    for (int version = 2; version <= 3; ++version) {
        if (!defs.empty() && version == 2) {
            system->message("Pre-definitions found, assuming version 3 syntax.");
            continue;       // Predefines are only allowed with v3 syntax
        }
        system->cfdgVersion = version;
        system->mFirstCfdgRead = true;
        if (!pCfdg)
            pCfdg = std::make_unique<CFDGImpl>(system);
        Builder b(pCfdg, variation);
        pCfdg->m_builder = &b;
        LatestCFDGimpl = pCfdg.get();

        yy::Scanner lexer;
        b.lexer = &lexer;
        lexer.driver = &b;
        lexer.startToken = version == 2 ? yy::CfdgParser::token::CFDG2 : 
                                          yy::CfdgParser::token::CFDG3;
        
        yy::CfdgParser parser(b);
        AbstractSystem::istr_ptr input;
        if (defs.empty()) {
            input = system->openFileForRead(fname);
        } else {
            defs.append("import \"");
            defs.append(fname);
            defs += '"';
            fname = "pre-defines buffer";
            input = std::make_unique<std::istringstream>(defs.c_str());
            b.mIncludeDepth = -1;   // pre-defs buffer is at level -1
        }
        if (!input || !input->good()) {
            system->error();
            system->message("Couldn't open rules file %s", fname);
            return nullptr;
        }
        
        b.m_CFDG->fileNames.push_back(fname);
        b.m_currentPath = &(b.m_CFDG->fileNames.back());
        {
#ifdef _MSC_VER
            static char dirchar = '\\';
#else
            static char dirchar = '/';
#endif
            auto dirptr = b.m_currentPath->find_last_of(dirchar);
            if (dirptr == std::string::npos)
                b.m_basePath = std::make_unique<std::string>(*b.m_currentPath);
            else
                b.m_basePath = std::make_unique<std::string>(*b.m_currentPath, 0, dirptr+1);
        }
        b.m_filesToLoad.push(b.m_currentPath);
        b.m_streamsToLoad.push(std::move(input));
        b.m_includeNamespace.push(false);
        b.push_repContainer(b.m_CFDG->mCFDGcontents);
        
        if (version == 2)
            system->message("Reading rules file %s", fname);

        lexer.yyrestart(b.m_streamsToLoad.top().get());
        //parser.set_debug_level(1);
        
        int yyresult = 0;
        try {
            yyresult = parser.parse();
        } catch (CfdgError& err) {
            system->syntaxError(err);
            LatestCFDGimpl = nullptr;
            return nullptr;
        }
        
        b.pop_repContainer(nullptr);    // pCfdg->mCFDGcontents

        if (b.mErrorOccured)
            return nullptr;
        if (yyresult == 0) {
            b.m_CFDG->rulesLoaded();
            if (b.mErrorOccured)
                return nullptr;
            break;
        }
        if (lexer.maybeVersion == 0 || 
            lexer.maybeVersion == (version == 2 ? yy::CfdgParser::token::CFDG2 : 
                                                  yy::CfdgParser::token::CFDG3))
            return nullptr;
        system->message("Restarting as a version 3 design");
        pCfdg.reset();
        LatestCFDGimpl = nullptr;
    }
    
    if (pCfdg) {
        pCfdg->m_builder = nullptr;
        system->message("%d rules loaded", pCfdg->numRules());
    }
    
    return cfdg_ptr(pCfdg);
}

// Sketchy as fuck, I know
#include "examples.h"