-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclass_loader.lua
More file actions
479 lines (366 loc) · 13.6 KB
/
class_loader.lua
File metadata and controls
479 lines (366 loc) · 13.6 KB
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
472
473
474
475
476
477
478
479
--[[-----------------------------------------------------------------------------
Copyright 2022 Thomas (Tom.bat) O'Sullivan
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at:
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-------------------------------------------------------------------------------]]
local function isstring(value)
return type(value) == "string"
end
local function istable(value)
return type(value) == "table"
end
local ClassLoader = {}
do
local type = type
local getmetatable = getmetatable
function ClassLoader.EnhancedType(object)
local typ = type(object)
if typ == "table" then
local objectType = object.__type
if objectType == "EnumValue" then
local declaringClass = object._declaringClass
if declaringClass then
typ = declaringClass.__name or typ
end
elseif objectType == "Enum" then
typ = object.__name .. "#Template"
elseif getmetatable(object) == nil then --This is an uninitialised class.
typ = object.__name and (object.__name .. "#Template") or typ
else
typ = object.__name or typ
end
end
return typ
end
end
local packages = {}
local currentPackage, currentFile
local baseDirectory
local function stripLastItemFromPackageName(packageName)
return packageName:sub(1,
-(#packageName:match("[^.]+$") --Get the length of the last item from the location
+ 2))
end
local function packageNameToObjectName(packageName)
return packageName
:match("[^.]+$") --Get the last item from the package name
:gsub("^%l", string.upper) --Capitalise first letter
:gsub("_%l", string.upper) --Capitalise every letter with an underscore before
:gsub("%_", "") --Remove all underscores
end
do
local function locationAsAbsolute(location)
return location:find(".", 1, true)
and location
or currentPackage.__name .. "." .. location
end
local function packageNameAsDirectoryPath(packageName)
return baseDirectory
.. packageName:gsub("%.", "/")
.. "/"
end
local function importPackage(packageName)
if not packages[packageName] then
ClassLoader.LoadDirectory(packageNameAsDirectoryPath(packageName), true)
end
local objects = {}
for objectName, object in pairs(packages[packageName]) do
if objectName:sub(0, 2) ~= "__" then
currentFile[objectName] = object
table.insert(objects, object)
end
end
return objects
end
local function addObjectToCurrentFile(objectPackage, objectName)
if not objectPackage[objectName] then
objectPackage[objectName] = {}
end
local object = objectPackage[objectName]
if currentFile then
currentFile[objectName] = object
end
return object
end
function ClassLoader.ImportObject(location)
assert(isstring(location), "Objects may only be imported by their location")
location = locationAsAbsolute(location)
local packageName = stripLastItemFromPackageName(location)
if location:sub(-1) == "*" then
return importPackage(packageName)
end
return addObjectToCurrentFile(ClassLoader.GetPackage(packageName),
packageNameToObjectName(location))
end
end
do
local function getCurrentFileObject()
return currentPackage[currentFile.__objectName]
end
local function instantiateClass(class)
assert(istable(class), "The class constructor must be called with a colon")
return setmetatable({}, class)
end
local Enum = {}
Enum.__type = "Enum"
Enum.__isEnum = true
Enum.__index = Enum
function Enum:GetValues()
return self._values
end
function Enum:GetValueOf(name)
local value = self[name]
if istable(value) and value.__type == "EnumValue" then
return value
end
end
local baseEnvironment = {
Import = ClassLoader.ImportObject,
Class = function()
local class = getCurrentFileObject()
class.__type = "Class"
class.__isClass = true
class.__index = class
class.New = instantiateClass
class.Extends = ClassLoader.ExtendObject
class.Property = ClassLoader.CreateProperty
return class
end,
Singleton = function()
local singleton = getCurrentFileObject()
singleton.__type = "Singleton"
singleton.__isSingleton = true
return singleton
end,
Enum = function()
return setmetatable(getCurrentFileObject(), Enum)
end
}
baseEnvironment.__index = baseEnvironment
setmetatable(baseEnvironment, {__index = _G})
function ClassLoader.GetPackage(packageName)
assert(isstring(packageName), "The package location must be provided as a string")
if packages[packageName] then
return packages[packageName]
end
local package = {
__name = packageName,
__type = "Package",
__isPackage = true,
_G = _G,
type = ClassLoader.EnhancedType,
pairs = pairs,
ipairs = ipairs
}
package.__index = package
setmetatable(package, baseEnvironment)
packages[packageName] = package
return package
end
end
function ClassLoader.ExtendObject(class, super)
assert(istable(class), "The class being extended must be a table")
if not istable(super) then
assert(isstring(super), "Classes may only be extended by objects or names")
super = ClassLoader.ImportObject(super)
assert(istable(super), "The super class name didn't resolve to an object")
end
class.__super = super
setmetatable(class, super)
return class
end
function ClassLoader.CreateProperty(class, name, typ, default)
assert(istable(class), "The property builder must be called with a colon")
assert(isstring(name), "The property name must be a string")
assert(typ == nil or isstring(typ), "The property type must be a string or nil")
local privateName = "_" .. name:gsub("^%u", string.lower)
class["Get" .. name] = function(self)
return self[privateName]
end
if typ then
class["Set" .. name] = function(self, value)
local actualType = ClassLoader.EnhancedType(value)
assert(actualType == typ, "Unexpected value of type \"" .. actualType .. "\" given for property: " .. name)
self[privateName] = value
end
else
class["Set" .. name] = function(self, value)
self[privateName] = value
end
end
if default then
class["Set" .. name](class, default)
end
return class
end
do
local function filePathToObjectPackageName(filePath)
return filePath
:sub(#baseDirectory + 1) --Strip the base directory
:sub(1, (filePath:sub(-4) == ".lua") and -5 or -1) --Strip the file extension if it's present
:gsub("%/", ".") --Replace all forward slashes with dots
end
local function filePathToObjectPackageAndName(filePath)
local location = filePathToObjectPackageName(filePath)
return stripLastItemFromPackageName(location),
packageNameToObjectName(location)
end
local function createFileEnvironment(filePath, packageName, objectName)
currentFile = setmetatable({
__objectName = objectName
}, currentPackage)
return currentFile
end
local EnumValue = {}
EnumValue.__type = "EnumValue"
EnumValue.__isEnumValue = true
EnumValue.__index = EnumValue
local function newEnumValue(name, value, declaringClass)
local tbl = setmetatable({}, EnumValue)
tbl._name = name
tbl._value = value
tbl._declaringClass = declaringClass
return tbl
end
function EnumValue:GetName()
return self._name
end
function EnumValue:GetValue()
return self._value
end
function EnumValue:GetDeclaringClass()
return self._declaringClass
end
function EnumValue:__add(other)
return self._value + other._value
end
function EnumValue:__sub(other)
return self._value - other._value
end
function EnumValue:__mul(other)
return self._value * other._value
end
function EnumValue:__div(other)
return self._value / other._value
end
function EnumValue:__mod(other)
return self._value % other._value
end
function EnumValue:__eq(other)
return self._value == other._value
end
function EnumValue:__lt(other)
return self._value < other._value
end
function EnumValue:__le(other)
return self._value <= other._value
end
local function setupEnum(enum)
local values = {}
for name, value in pairs(enum) do
if name:sub(0, 2) ~= "__" then --Ignore type, isEnum, etc
local enumValue = newEnumValue(name, value, enum)
enum[name] = enumValue
table.insert(values, enumValue)
end
end
enum._values = values
end
local function registerObject(packageName, objectName, object)
assert(istable(object), "Invalid object returned by: " .. packageName .. "." .. objectName)
object.__name = objectName
object.__package = packageName
if object.Extends == ClassLoader.ExtendObject then
object.Extends = nil
end
if object.Property == ClassLoader.CreateProperty then
object.Property = nil
end
if object.__type == "Enum" then
setupEnum(object)
end
currentPackage[objectName] = object
end
local function getDirectoryContents(directory)
local files, directories = {}, {}
for fileName in io.popen("ls -pUqAL '" .. directory .. "'"):lines() do
if fileName:sub(-4) == ".lua" then
table.insert(files, fileName)
elseif fileName:sub(-1) == "/" then
table.insert(directories, fileName)
end
end
return files, directories
end
local function preparePackage(directory, files)
local packageName = filePathToObjectPackageName(directory):sub(1, -2)
local package = ClassLoader.GetPackage(packageName)
for _, fileName in ipairs(files) do
local objectName = packageNameToObjectName(fileName:sub(1, -5))
package[objectName] = package[objectName] or {}
end
return package
end
local function loadFile(filePath)
local packageName, objectName = filePathToObjectPackageAndName(filePath)
local file = loadfile(filePath)
debug.setfenv(file, createFileEnvironment(filePath, packageName, objectName))
registerObject(packageName, objectName, file())
end
local function loadDirectory(directory, importMode)
assert(isstring(directory), "The directory to load must be provided as a string")
local files, directories = getDirectoryContents(directory)
if importMode then
preparePackage(directory, files)
return
else
currentPackage = preparePackage(directory, files)
end
for i, fileName in ipairs(files) do
loadFile(directory .. fileName)
end
for i, directoryName in ipairs(directories) do
loadDirectory(directory .. directoryName)
end
end
ClassLoader.LoadDirectory = loadDirectory
end
do
local function cleanUpPackages()
for packageName, package in pairs(packages) do
setmetatable(package, nil)
packages[packageName] = nil
for key, _ in pairs(package) do
if key:sub(0, 2) ~= "__" then --If our package only contains metadata it's safe to delete
packages[packageName] = package
break
end
end
end
end
local function callEntryPoint(classLocation)
local startClass = ClassLoader.ImportObject(classLocation)
assert(startClass.__type, "The start class couldn't be found at: " .. classLocation)
assert(startClass.__isSingleton, "The start class may only be a singleton")
assert(startClass.Main, "The start class doesn't have a main method")
startClass:Main()
end
function ClassLoader.Bootstrap(directory, startClassLocation)
assert(isstring(directory), "The base directory must be provided as a string")
assert(isstring(startClassLocation), "The start class location must be provided as a string")
baseDirectory = directory:sub(-1) == "/" and directory or directory .. "/"
ClassLoader.LoadDirectory(baseDirectory)
cleanUpPackages()
callEntryPoint(startClassLocation)
currentPackage, currentFile, baseEnvironment = nil, nil, nil
collectgarbage()
end
end
return ClassLoader