summaryrefslogtreecommitdiffstats
path: root/lib/puppet/parser/scope.rb
blob: 37e5c39b77184feac099b1a726ae6afd175c5993 (plain)
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
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
# The scope class, which handles storing and retrieving variables and types and
# such.

require 'puppet/transportable'

module Puppet
    module Parser
        class Scope
            include Enumerable
            attr_accessor :parent, :level, :interp
            attr_accessor :name, :type

            # The global host table.  This will likely be changed to be scoped,
            # eventually, but for now it's not.
            @@hosttable = {}

            # Whether we behave declaratively.  Note that it's a class variable,
            # so all scopes behave the same.
            @@declarative = true

            # Retrieve and set the declarative setting.
            def Scope.declarative
                return @@declarative
            end

            def Scope.declarative=(val)
                @@declarative = val
            end

            # Create a new child scope.
            def child=(scope)
                @children.push(scope)
            end

            # Test whether a given scope is declarative.  Even though it's
            # a global value, the calling objects don't need to know that.
            def declarative?
                @@declarative
            end

            # Is this scope associated with being a node?  The answer determines
            # whether we store class instances here
            def nodescope?
                @nodescope
            end

            def nodescope=(bool)
                @nodescope = bool
            end

            # Are we the top scope?
            def topscope?
                @level == 1
            end

            # Yield each child scope in turn
            def each
                @children.each { |child|
                    yield child
                }
            end

            # Initialize our new scope.  Defaults to having no parent and to
            # being declarative.
            def initialize(parent = nil, declarative = true)
                @parent = parent
                @nodescope = false

                if @parent.nil?
                    @level = 1
                    @@declarative = declarative
                else
                    @parent.child = self
                    @level = @parent.level + 1
                    @interp = @parent.interp
                end

                # Our child scopes
                @children = []

                # The symbol table for this scope
                @symtable = Hash.new(nil)

                # The type table for this scope
                @typetable = Hash.new(nil)

                # The table for storing class singletons.  This will only actually
                # be used by top scopes and node scopes.
                @classtable = Hash.new(nil)

                # All of the defaults set for types.  It's a hash of hashes,
                # with the first key being the type, then the second key being
                # the parameter.
                @defaultstable = Hash.new { |dhash,type|
                    dhash[type] = Hash.new(nil)
                }

                # The object table is similar, but it is actually a hash of hashes
                # where the innermost objects are TransObject instances.
                @objectable = Hash.new { |typehash,typekey|
                    #hash[key] = TransObject.new(key)
                    typehash[typekey] = Hash.new { |namehash, namekey|
                        #Puppet.debug("Creating iobject with name %s and type %s" %
                        #    [namekey,typekey])
                        namehash[namekey] = TransObject.new(namekey,typekey)
                        @children.push namehash[namekey]

                        # this has to be last, because the return value of the
                        # block is the actual hash
                        namehash[namekey]
                    }
                }

                # Map the names to the tables.
                @map = {
                    "variable" => @symtable,
                    "type" => @typetable,
                    "object" => @objectable,
                    "defaults" => @defaultstable
                }
            end

            # This method abstracts recursive searching.  It accepts the type
            # of search being done and then either a literal key to search for or
            # a Proc instance to do the searching.
            def lookup(type,sub)
                table = @map[type]
                if table.nil?
                    error = Puppet::ParseError.new(
                        "Could not retrieve %s table at level %s" %
                            [type,self.level]
                    )
                    error.stack = caller
                    raise error
                end

                if sub.is_a?(Proc) and obj = sub.call(table)
                    return obj
                elsif table.include?(sub)
                    return table[sub]
                elsif ! @parent.nil?
                    return @parent.lookup(type,sub)
                else
                    return :undefined
                end
            end

            # Look up a given class.  This enables us to make sure classes are
            # singletons
            def lookupclass(klass)
                if self.nodescope? or self.topscope?
                    return @classtable[klass]
                else
                    unless @parent
                        raise Puppet::DevError, "Not top scope but not parent defined"
                    end
                    return @parent.lookupclass(klass)
                end
            end

            # Look up hosts from the global table.
            def lookuphost(name)
                if @@hosttable.include?(name)
                    return @@hosttable[name]
                else
                    return nil
                end
            end

            # Collect all of the defaults set at any higher scopes.
            # This is a different type of lookup because it's additive --
            # it collects all of the defaults, with defaults in closer scopes
            # overriding those in later scopes.
            def lookupdefaults(type)
                values = {}

                # first collect the values from the parents
                unless @parent.nil?
                    @parent.lookupdefaults(type).each { |var,value|
                        values[var] = value
                    }
                end

                # then override them with any current values
                # this should probably be done differently
                if @defaultstable.include?(type)
                    @defaultstable[type].each { |var,value|
                        values[var] = value
                    }
                end
                #Puppet.debug "Got defaults for %s: %s" %
                #    [type,values.inspect]
                return values
            end

            # Look up a defined type.
            def lookuptype(name)
                Puppet.debug "Looking up type %s" % name
                value = self.lookup("type",name)
                if value == :undefined
                    return nil
                else
                    Puppet.debug "Found type %s" % name
                    return value
                end
            end

            # Look up an object by name and type.
            def lookupobject(name,type)
                Puppet.debug "Looking up object %s of type %s in level %s" %
                    [name, type, @level]
                unless defined? @@objectsearch
                    @@objectsearch = proc { |table|
                        if table.include?(type)
                            if table[type].include?(name)
                                table[type][name]
                            end
                        else
                            nil
                        end
                    }
                end
                value = self.lookup("object",@@objectsearch)
                if value == :undefined
                    return nil
                else
                    return value
                end
            end

            # Look up a variable.  The simplest value search we do.
            def lookupvar(name)
                Puppet.debug "Looking up variable %s" % name
                value = self.lookup("variable", name)
                if value == :undefined
                    error = Puppet::ParseError.new(
                        "Undefined variable '%s'" % name
                    )
                    error.stack = caller
                    raise error
                else
                    #Puppet.debug "Value of '%s' is '%s'" % [name,value]
                    return value
                end
            end

            # Create a new scope.
            def newscope
                Puppet.debug "Creating new scope, level %s" % [self.level + 1]
                return Puppet::Parser::Scope.new(self)
            end

            # Store the fact that we've evaluated a given class.
            # FIXME Shouldn't setclass actually store the code, not just a boolean?
            def setclass(klass)
                if self.nodescope? or self.topscope?
                    @classtable[klass] = true
                else
                    @parent.setclass(klass)
                end
            end

            # Set defaults for a type.  The typename should already be downcased,
            # so that the syntax is isolated.
            def setdefaults(type,params)
                table = @defaultstable[type]

                # if we got a single param, it'll be in its own array
                unless params[0].is_a?(Array)
                    params = [params]
                end

                params.each { |ary|
                    Puppet.debug "Default for %s is %s => %s" %
                        [type,ary[0].inspect,ary[1].inspect]
                    if @@declarative
                        if table.include?(ary[0])
                            error = Puppet::ParseError.new(
                                "Default already defined for %s { %s }" %
                                    [type,ary[0]]
                            )
                            error.stack = caller
                            raise error
                        end
                    else
                        if table.include?(ary[0])
                            # we should maybe allow this warning to be turned off...
                            Puppet.warning "Replacing default for %s { %s }" %
                                [type,ary[0]]
                        end
                    end
                    table[ary[0]] = ary[1]
                }
            end

            # Store a host in the global table.
            def sethost(name,host)
                if @@hosttable.include?(name)
                    str = "Host %s is already defined" % name
                    if @@hosttable[name].file
                        str += " in file %s" % @@hosttable[name].file
                    end
                    if @@hosttable[name].line
                        str += " on line %s" % @@hosttable[name].line
                    end
                    raise Puppet::ParseError,
                        "Host %s is already defined" % name
                else
                    @@hosttable[name] = host
                end
            end

            # Define our type.
            def settype(name,ltype)
                @typetable[name] = ltype
            end

            # Return an interpolated string.
            # FIXME We do not yet support a non-interpolated string.
            def strinterp(string)
                newstring = string.dup
                regex = Regexp.new('\$\{(\w+)\}|\$(\w+)')
                #Puppet.debug("interpreting '%s'" % string)
                while match = regex.match(newstring) do
                    if match[1]
                        newstring.sub!(regex,self.lookupvar(match[1]).to_s)
                    elsif match[2]
                        newstring.sub!(regex,self.lookupvar(match[2]).to_s)
                    else
                        raise Puppet::DevError, "Could not match variable in %s" %
                            newstring
                    end
                end
                #Puppet.debug("result is '%s'" % newstring)
                return newstring
            end

            # This is kind of quirky, because it doesn't differentiate between
            # creating a new object and adding params to an existing object.
            # It doesn't solve the real problem, though: cases like file recursion,
            # where one statement explicitly modifies an object, and another
            # statement modifies it because of recursion.
            def setobject(type, name, params, file, line)
                obj = self.lookupobject(name,type)
                if obj == :undefined or obj.nil?
                    obj = @objectable[type][name]

                    # only set these if we've created the object, which is the
                    # most common case
                    obj.file = file
                    obj.line = line
                end

                # now add the params to whatever object we've found, whether
                # it was in a higher scope or we just created it
                # it will not be obvious where these parameters are from, that is,
                # which file they're in or whatever
                params.each { |var,value|
                    obj[var] = value
                }
                return obj
            end

            # Set a variable in the current scope.  This will override settings
            # in scopes above, but will not allow variables in the current scope
            # to be reassigned if we're declarative (which is the default).
            def setvar(name,value)
                Puppet.debug "Setting %s to '%s' at level %s" %
                    [name.inspect,value,self.level]
                if @@declarative and @symtable.include?(name)
                    error = Puppet::ParseError.new(
                        "Cannot reassign variable %s" % name
                    )
                    error.stack = caller
                    raise error
                else
                    if @symtable.include?(name)
                        Puppet.warning "Reassigning %s to %s" % [name,value]
                    end
                    @symtable[name] = value
                end
            end

            # Convert our scope to a list of Transportable objects.
            def to_trans
                Puppet.debug "Translating scope %s at level %s" %
                    [self.object_id,self.level]

                results = []
                
                # Iterate across our child scopes and call to_trans on them
                @children.each { |child|
                    if child.is_a?(Scope)
                        cresult = child.to_trans
                        Puppet.debug "Got %s from scope %s" %
                            [cresult.class,child.object_id]

                        # Scopes normally result in a TransBucket, but they could
                        # also result in a normal array; if that happens, get rid
                        # of the array.
                        unless cresult.is_a?(TransBucket)
                            cresult.each { |result|
                                results.push(result)
                            }
                        else
                            # Otherwise, just add it to our list of results.
                            results.push(cresult)
                        end
                    elsif child.is_a?(TransObject)
                        results.push(child)
                    else
                        error = Puppet::DevError.new(
                            "Puppet::Parse::Scope cannot handle objects of type %s" %
                                child.class
                        )
                        error.stack = caller
                        raise error
                    end
                }

                # Get rid of any nil objects.
                results = results.reject { |child|
                    child.nil?
                }

                # If we have a name and type, then make a TransBucket, which
                # becomes a component.
                # Else, just stack all of the objects into the current bucket.
                if defined? @name
                    bucket = TransBucket.new
                    bucket.name = @name

                    # it'd be nice not to have to do this...
                    results.each { |result|
                        #Puppet.debug "Result type is %s" % result.class
                        bucket.push(result)
                    }
                    if defined? @type
                        bucket.type = @type
                    else
                        error = Puppet::ParseError.new(
                            "No type for scope %s" % @name
                        )
                        error.stack = caller
                        raise error
                    end
                    Puppet.debug "TransBucket with name %s and type %s in scope %s" %
                        [@name,@type,self.object_id]

                    # now find metaparams
                    @symtable.each { |var,value|
                        if Puppet::Type.metaparam?(var.intern)
                            #Puppet.debug("Adding metaparam %s" % var)
                            bucket.param(var,value)
                        else
                            #Puppet.debug("%s is not a metaparam" % var)
                        end
                    }
                    #Puppet.debug "Returning bucket %s from scope %s" %
                    #    [bucket.name,self.object_id]
                    return bucket
                else
                    #Puppet.debug "nameless scope; just returning a list"
                    return results
                end
            end
        end
    end
end

# $Id$