]> git.donarmstrong.com Git - lilypond.git/blob - lily/lily-modules.cc
Issue 4462/1: Create a module variable access system for C++
[lilypond.git] / lily / lily-modules.cc
1 /*
2   This file is part of LilyPond, the GNU music typesetter.
3
4   Copyright (C) 2015 by David Kastrup <dak@gnu.org>
5
6   LilyPond is free software: you can redistribute it and/or modify
7   it under the terms of the GNU General Public License as published by
8   the Free Software Foundation, either version 3 of the License, or
9   (at your option) any later version.
10
11   LilyPond is distributed in the hope that it will be useful,
12   but WITHOUT ANY WARRANTY; without even the implied warranty of
13   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14   GNU General Public License for more details.
15
16   You should have received a copy of the GNU General Public License
17   along with LilyPond.  If not, see <http://www.gnu.org/licenses/>.
18 */
19
20 #include "lily-modules.hh"
21
22 struct Scm_module::Variable_record
23 {
24   const char *name_;
25   Scm_variable *var_;
26   Variable_record *next_;
27   Variable_record (const char *name, Scm_variable *var, Variable_record *next_)
28     : name_ (name), var_ (var), next_ (next_)
29   { }
30 };
31
32 void
33 Scm_module::register_variable (const char *name, Scm_variable *var)
34 {
35   variables_ = new Variable_record (name, var, variables_);
36 }
37
38 Scm_module::Scm_module (const char *name)
39   : name_ (name), module_ (SCM_UNDEFINED), variables_ (0)
40 {
41 }
42
43 void
44 Scm_module::boot_init (void *arg)
45 {
46   Scm_module *self = static_cast<Scm_module *> (arg);
47
48   // Establish variables first
49   for (Variable_record *p = self->variables_; p;)
50     {
51       Variable_record *next = p->next_;
52       p->var_->boot (p->name_);
53       delete p;
54       p = next;
55     }
56   self->variables_ = 0;
57 }
58
59 void
60 Scm_module::boot ()
61 {
62   assert (SCM_UNBNDP (module_));
63   module_ = scm_c_define_module (name_, boot_init, static_cast <void *> (this));
64 }
65
66 void
67 Scm_module::import ()
68 {
69   assert (SCM_UNBNDP (module_));
70   module_ = scm_c_resolve_module (name_);
71   for (Variable_record *p = variables_; p;)
72     {
73       Variable_record *next = p->next_;
74       p->var_->import (module_, p->name_);
75       delete p;
76       p = next;
77     }
78   variables_ = 0;
79 }
80
81 void
82 Scm_variable::boot (const char *name)
83 {
84   assert (!SCM_VARIABLEP (var_));
85   var_ = scm_c_define (name, var_);
86 }
87
88 void
89 Scm_variable::import (SCM module, const char *name)
90 {
91   assert (SCM_UNBNDP (var_));
92   var_ = scm_c_module_lookup (module, name);
93 }
94
95
96 Scm_variable::Scm_variable (Scm_module &m, const char *name, SCM value)
97   : var_ (value)
98 {
99   assert (SCM_IMP (value));
100   m.register_variable (name, this);
101 }