-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclsVBAProcedure.cls
More file actions
430 lines (387 loc) · 19.1 KB
/
Copy pathclsVBAProcedure.cls
File metadata and controls
430 lines (387 loc) · 19.1 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
VERSION 1.0 CLASS
BEGIN
MultiUse = -1 'True
END
Attribute VB_Name = "clsVBAProcedure"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = False
Attribute VB_Exposed = False
'@Exposed
'@Folder "1-Inicio e Instalacion.Gestion de modulos y procs"
'@IgnoreModule MissingAnnotationArgument
Option Explicit
Public Name As String
Public Module As String
Public ContainerType As ProcContainerType
Public bPrivateModule As Boolean
Public strCode As String
Public procNumLines As Long
Public procSignatureLine As Long
Public procStartLine As Long
Public PKind As ProcKind
Public NormalizedSignature As String
Public ProcedureType As ProcType ' Macro (Sub sin params), UDF (Function no Private), Function, Sub con params
Public Scope As String ' ambito al que se aplica: selección, hoja activa, libro activo, argumentos de la funcion, ...
Public ArgumentDescriptions As String ' Separado por "|"
Public Returns As String ' Qué devuelve
Public HasMetadata As Boolean ' TRUE si tiene comentarios @UDF
Public Description As String
Public Category As String
Public Example As String ' Ejemplo de uso
Public Raises As String ' Errores que puede lanzar
Public Dependencies As String ' Dependencias de otros procedimientos
' Constructor para fácil inicialización
'TODO: revisar el codigo para evitar las restricciones en el orden de las llamadas
Public Sub Init(ByVal modl As String, ByVal bModuloPrivado_ As Boolean, ByVal ContainerType_ As ProcContainerType, _
ByVal PKind_ As ProcKind, ByVal procName As String, CodeBlock As T_CodeBlock)
On Error GoTo ErrorHandler
Name = procName
Module = modl
ContainerType = ContainerType_
bPrivateModule = bModuloPrivado_
strCode = CodeBlock.strCode
procNumLines = CodeBlock.procNumLines
procSignatureLine = CodeBlock.procSignatureLine
procStartLine = CodeBlock.procStartLine
PKind = PKind_
' Es IMPORTANTE mantener el orden de estas llamadas! (al menos de momento, PTE de mejorar)
NormalizedSignature = NormalizarLineasFirma(CodeBlock.strCode, CodeBlock.procSignatureLine - CodeBlock.procStartLine + 1)
ProcedureType = TipoProcedimiento(NormalizedSignature)
Scope = ParsearCodeParaDeducirContexto(CodeBlock.strCode)
ArgumentDescriptions = ComponerArgumentDescriptions(NormalizedSignature)
Dim arrMetadata()
arrMetadata = ParsearMetadataCompleta(CodeBlock.strCode)
' VALIDACION DE METADATOS: deben corresponder a los deducidos del procedimiento... o extenderlos.
Dim procTypeTag As String
Select Case ProcedureType
Case eventHandler
procTypeTag = "(VBA, Manejador de eventos) "
Case internalPrivate, internalSubPublicWithParams
procTypeTag = "(VBA, Interna, no expuesta) "
End Select
Description = arrMetadata(0)
If Left(Description, Len(procTypeTag)) <> procTypeTag Then Description = procTypeTag & Description
' Si no hay descripción del procedimiento, generar una básica
If Description = "" Then
Description = GenerarDescripcionAutomatica(Name)
End If
' validar metadatos, con los deducidos de la firma y contenido del codigo
If arrMetadata(1) <> "" And InStr(arrMetadata(1), Category) = 0 Then
Category = Category & vbCrLf & "M.D.:" & arrMetadata(1)
End If
If arrMetadata(2) <> "" And InStr(arrMetadata(2), ArgumentDescriptions) = 0 Then
ArgumentDescriptions = ArgumentDescriptions & vbCrLf & "M.D.:" & arrMetadata(2)
End If
If arrMetadata(3) <> "" And InStr(arrMetadata(3), Scope) = 0 Then
Scope = Scope & vbCrLf & "M.D.:" & arrMetadata(3)
End If
If arrMetadata(4) <> "" And InStr(arrMetadata(4), Returns) = 0 Then
Returns = Returns & vbCrLf & "M.D.:" & arrMetadata(4)
End If
'Debug.Print "[clsVBAProcedure Init] - " & dumpProcedimiento
Exit Sub
ErrorHandler:
Debug.Print "[clsVBAProcedure Init] - Error: " & Err.Description
End Sub
'@Description: Determina si una función es visible para excel como macro o udf, o si es "interna",
' a partir de NormalizedSignature,PKind,ContainerType,bModuloPrivado,...
Private Function TipoProcedimiento(ByVal firmaNormalizada As String) As ProcType
Dim tipo As String, acceso As String
Dim re As Object: Set re = CreateObject("VBScript.RegExp")
re.IgnoreCase = True
' Acceso
Set re = Nothing: Set re = CreateObject("VBScript.RegExp")
On Error GoTo ErrorHandler
re.Pattern = "^\s*((?:(?:Public|Private|Friend|Static)\s+){1,2})?\s*(Function|Sub|Property\s+(?:Get|Set|Let))\s*(\S+)\s*\(\s*(.*)\)"
If re.Test(firmaNormalizada) Then
Dim m As Object: Set m = re.Execute(firmaNormalizada)(0)
acceso = Replace(LCase$(Trim$(m.SubMatches(0))), " static", "")
tipo = LCase$(Trim$(m.SubMatches(1)))
Else
'Stop
End If
If acceso = "" Then acceso = "public"
If InStr(m.SubMatches(2), "_") > 0 Then
TipoProcedimiento = ProcType.eventHandler
' Normalmente deberían ser privados, dentro de una clase que instancie un objeto de otra clase que implemente eventos
'If acceso <> "private" Then Stop
' y no se si puede llegar a haber manejadores que sean funciones... por si acaso:
'If tipo <> "sub" Then Stop
ElseIf tipo = "sub" And acceso = "public" And Not bPrivateModule And ContainerType = StdModule _
And m.SubMatches(3) <> "" Then
TipoProcedimiento = ProcType.internalSubPublicWithParams
ElseIf acceso <> "public" Or bPrivateModule Or ContainerType <> StdModule Or InStr(tipo, "property") > 0 Then
TipoProcedimiento = ProcType.internalPrivate
Else
Select Case LCase$(tipo)
Case "sub"
TipoProcedimiento = ProcType.Macro
Case "function"
TipoProcedimiento = ProcType.udf
Case Else
Debug.Print "[TipoProcedimiento] - Error al procesar Firma Normalizada con expresiones regulares"
Stop ' depurar la causa
End Select
End If
' FIXME: establece los valores de PKind y Returns, en funcion del parsing realizado en este procedimiento
If tipo = "function" Then
If PKind = ProcKind.proc Then PKind = ProcKind.ProcFunction Else Stop ' debug
ElseIf InStr(tipo, "property") > 0 And (PKind < ProcKind.PropLet Or PKind < ProcKind.PropGet) Then
If InStr(tipo, "let") > 0 Then
PKind = ProcKind.PropLet
ElseIf InStr(tipo, "set") > 0 Then
PKind = ProcKind.PropSet
ElseIf InStr(tipo, "get") > 0 Then
PKind = ProcKind.PropGet
Else
Stop ' debug
End If
ElseIf tipo = "sub" Then
Returns = DEFAULT_NORETURNS
If PKind = ProcKind.proc Then
PKind = ProcKind.ProcSub
Else
Stop ' debug
End If
End If
If PKind = ProcSub Then Returns = DEFAULT_NORETURNS
Exit Function
ErrorHandler:
Debug.Print "[TipoProcedimiento] - Error al procesar Code con expresiones regulares: " & Err.Description
End Function
'@Description: Determina si una función es visible para excel como macro o udf, o si es "interna",
' a partir de NormalizedSignature,PKind,ContainerType,bModuloPrivado,...
Private Function ParsearCodeParaDeducirContexto(CodeText As String) As String
Dim re As Object
Set re = CreateObject("VBScript.RegExp")
re.Global = True
re.IgnoreCase = True
re.Pattern = "\bThisWorkBook\b"
' lo siguiente sería una 'condicion de error' muy probable: no debería, en general, manipular el XLAM
If re.Test(CodeText) Then
If ParsearCodeParaDeducirContexto <> "" Then _
ParsearCodeParaDeducirContexto = ParsearCodeParaDeducirContexto & "|"
ParsearCodeParaDeducirContexto = "ThisWorkbook"
End If
re.Pattern = "\bSelection\b"
If re.Test(CodeText) Then
If ParsearCodeParaDeducirContexto <> "" Then _
ParsearCodeParaDeducirContexto = ParsearCodeParaDeducirContexto & "|"
ParsearCodeParaDeducirContexto = "Selection"
End If
re.Pattern = "\bActiveWorkbook\b"
If re.Test(CodeText) Then
If ParsearCodeParaDeducirContexto <> "" Then _
ParsearCodeParaDeducirContexto = ParsearCodeParaDeducirContexto & "|"
ParsearCodeParaDeducirContexto = ParsearCodeParaDeducirContexto & "ActiveWorkbook"
End If
re.Pattern = "\bActiveSheet\b"
If re.Test(CodeText) Then
If ParsearCodeParaDeducirContexto <> "" Then _
ParsearCodeParaDeducirContexto = ParsearCodeParaDeducirContexto & "|"
ParsearCodeParaDeducirContexto = ParsearCodeParaDeducirContexto & "ActiveSheet"
End If
re.Pattern = "\b(?:Range|Cells)\b"
If re.Test(CodeText) Then
If ParsearCodeParaDeducirContexto <> "" Then _
ParsearCodeParaDeducirContexto = ParsearCodeParaDeducirContexto & "|"
ParsearCodeParaDeducirContexto = ParsearCodeParaDeducirContexto & "Cells Range"
End If
End Function
'@Description: Normaliza firma del procedimiento: elimina continuaciones "_" y deja la firma en una sola línea
Private Function NormalizarLineasFirma(ByVal raw As String, ByVal SignatureLine As Long) As String
' raw: texto del codio, con cabecera de procedimiento, e incluso varias líneas que conforman la firma (puede contener vbCrLf y "_" al final de líneas)
Dim s As String
s = raw
' eliminar vbCrLf que tienen _ al final, y unir
Dim re As Object
Set re = CreateObject("VBScript.RegExp")
re.Global = True
re.IgnoreCase = True
On Error GoTo ErrHandler ' & "," & SignatureLine
re.Pattern = "^(?:.*(?:\r\n|\n|\r)){" & SignatureLine - 1 & "}" _
& "(.+(?:_\s*(?:\r\n|\n|\r).+)*\))"
s = re.Execute(s).Item(0).SubMatches(0)
' Quitar secuencias de continuation: " _" al final de línea + CRLF -> vacío
re.Pattern = "_\s*(\r\n|\n|\r)"
s = re.Replace(s, " ")
' ahora sustituir saltos de línea sobrantes por espacio y normalizar espacios
re.Pattern = "(\r\n|\n|\r)"
s = re.Replace(s, " ")
' colapsar múltiples espacios
re.Pattern = "\s+"
s = Trim$(re.Replace(s, " "))
NormalizarLineasFirma = s
Exit Function
ErrHandler:
Debug.Print "[NormalizarLineasFirma] - Error al procesar Code con expresiones regulares: " & Err.Description
End Function
'@Description: Extrae contenido entre paréntesis de una firma normalizada y reemplaza comas por "|"
Private Function ComponerArgumentDescriptions(ByVal firmaNormalizada As String) As String
Dim re As Object: Set re = CreateObject("VBScript.RegExp")
re.Pattern = "^[^'\(]+\((.*?)\)\s*(?:'.+)?$"
If re.Test(firmaNormalizada) Then
Dim args As String
args = Trim$(re.Execute(firmaNormalizada)(0).SubMatches(0))
If args = "" Then
ComponerArgumentDescriptions = DEFAULT_NOARGS
Else
' remplazar "," por "|", respetando que pueda haber comas dentro de literales (caso raro en VBA)
' asumimos que no hay comas embebidas; si las hubiera, se necesitaría parsing más sofisticado.
re.Pattern = "\s*,\s*"
ComponerArgumentDescriptions = re.Replace(args, "|")
End If
Else
ComponerArgumentDescriptions = DEFAULT_NOARGS
End If
End Function
' Parsea metadatos de comentarios estructurados (@Description, @Category, etc.)
' Soporta formatos:
' '@Tag: Valor
' '@Tag("Valor")
' '@Tag "Valor"
Private Function ParsearMetadataCompleta(CodeText As String)
Dim lineText As Variant
Dim regEx As Object
Dim matches As Object
Dim sDescription As String, sCategory As String, sArgumentDescriptions As String
Dim sScope As String, sReturns As String, sExample As String
Dim sRaises As String, sDependencies As String
' Inicializar con valores por defecto
HasMetadata = False
sDescription = ""
sCategory = DEFAULT_CATEGORY
sArgumentDescriptions = ""
sScope = ""
sReturns = ""
sExample = ""
sRaises = ""
sDependencies = ""
' Configurar expresion regular
Set regEx = CreateObject("VBScript.RegExp")
regEx.IgnoreCase = True ' Ahora ignora mayusculas/minusculas
Dim tag As String, Value As String
' Procesar hacia delante
For Each lineText In Split(CodeText, vbCrLf)
If lineText <> "" Then
' Patron extendido que soporta:
' '@Tag: Valor
' '@Tag("Valor")
' '@Tag "Valor"
' Tags soportados: UDF, Macro, Description, Note, Nota, Scope, Category, Dependencies,
' ArgumentDescriptions, Param, Returns, Return, Example, Raises, Throws
regEx.Pattern = "^\s*'\s*(?:['\s=\-_]+|(?:@\s*(UDF|Macro|Description|Note|Nota|Scope|Category|Dependencies|ArgumentDescriptions|Param|Returns|Return|Example|Raises|Throws)(?:\s*[:\s])?))?\s*(.*?)\s*$"
Set matches = regEx.Execute(lineText)
If matches.Count = 0 Then Exit For
If matches(0).SubMatches(0) <> "" Then
tag = matches(0).SubMatches(0) ' La palabra clave (UDF, Description, etc.)
End If
Value = Trim(matches(0).SubMatches(1)) ' El valor
' Extraer valor de formatos ("valor") o "valor"
regEx.Pattern = "^\s*\(?\s*""(.*?)""\s*\)?\s*$"
If regEx.Test(Value) Then Value = regEx.Execute(Value).Item(0).SubMatches(0)
' Tambien soportar formato con comillas simples ('valor')
If Value = "" Then
regEx.Pattern = "^\s*\(?\s*'(.*?)'\s*\)?\s*$"
If regEx.Test(Trim(matches(0).SubMatches(1))) Then
Value = regEx.Execute(Trim(matches(0).SubMatches(1))).Item(0).SubMatches(0)
End If
End If
Select Case UCase$(tag)
Case "UDF", "MACRO"
HasMetadata = True
Case "DESCRIPTION", "NOTE", "NOTA"
If sDescription <> "" Then sDescription = sDescription & " "
sDescription = sDescription & Value
Case "SCOPE"
If sScope <> "" Then sScope = sScope & " "
sScope = sScope & Value
Case "RETURNS", "RETURN"
If sReturns <> "" Then sReturns = sReturns & " "
sReturns = sReturns & Value
Case "CATEGORY"
If sCategory <> DEFAULT_CATEGORY And sCategory <> "" Then sCategory = sCategory & " "
If sCategory = DEFAULT_CATEGORY Then sCategory = ""
sCategory = sCategory & Value
Select Case LCase$(sCategory)
Case "hidden", "oculta", "ocultar", "-1"
sCategory = "-1"
End Select
Case "ARGUMENTDESCRIPTIONS", "PARAM"
If sArgumentDescriptions <> "" Then sArgumentDescriptions = sArgumentDescriptions & "|"
sArgumentDescriptions = sArgumentDescriptions & Value
Case "DEPENDENCIES"
If sDependencies <> "" Then sDependencies = sDependencies & "|"
sDependencies = sDependencies & Value
Case "EXAMPLE"
If sExample <> "" Then sExample = sExample & vbCrLf
sExample = sExample & Value
Case "RAISES", "THROWS"
If sRaises <> "" Then sRaises = sRaises & "|"
sRaises = sRaises & Value
Case Else ' comentarios SIN TAG: se atribuyen a Description
If Value <> "" Then
If sDescription <> "" Then sDescription = sDescription & ". "
sDescription = sDescription & Value
End If
End Select
End If
Next
' Asignar propiedades de la clase
Example = sExample
Raises = sRaises
Dependencies = sDependencies
ParsearMetadataCompleta = Array(sDescription, sCategory, sArgumentDescriptions, sScope, sReturns)
End Function
'@Description: Genera descripción automática basada en el nombre de la función
Private Function GenerarDescripcionAutomatica(ByVal nombreFuncion As String) As String
If InStr(nombreFuncion, "_") > 0 Then GenerarDescripcionAutomatica = "(manejador de evento " & nombreFuncion & ")": Exit Function
Dim re As Object: Set re = CreateObject("VBScript.RegExp")
re.Global = True
re.IgnoreCase = False
re.Pattern = "([A-Z]+[a-z]*)"
GenerarDescripcionAutomatica = Trim$(re.Replace(nombreFuncion, " $1")) & " (función personalizada)"
Select Case PKind
Case PropGet: GenerarDescripcionAutomatica = "Get " & GenerarDescripcionAutomatica
Case PropLet: GenerarDescripcionAutomatica = "Let " & GenerarDescripcionAutomatica
Case PropSet: GenerarDescripcionAutomatica = "Set " & GenerarDescripcionAutomatica
End Select
End Function
Private Function dumpProcedimiento()
Dim strdbg As String, strGen As String
dumpProcedimiento = "Procedimiento: " & Name & ", en " & Module & vbCrLf & vbTab
Select Case PKind
Case PropGet: strdbg = strdbg & "property get"
Case PropLet: strdbg = strdbg & "property let"
Case PropSet: strdbg = strdbg & "property set"
Case proc: strdbg = strdbg & "procedimiento"
Case ProcSub: strdbg = strdbg & "Sub"
Case ProcFunction: strdbg = strdbg & "Function"
End Select
strdbg = "en "
Select Case ContainerType
Case StdModule: strdbg = strdbg & "módulo estandar": strGen = "o"
Case ClassModule: strdbg = strdbg & "módulo de clase": strGen = "o"
Case Form: strdbg = strdbg & "formulario": strGen = "o"
Case Sheet: strdbg = strdbg & "hoja de excel": strGen = "a"
End Select
strdbg = strdbg & " " & IIf(bPrivateModule, "privad", "públic") & strGen
strdbg = IIf(ProcedureType = Macro, "Macro", IIf(ProcedureType = udf, "UDF", "interno a VBA")) & " (" & strdbg & ")"
dumpProcedimiento = dumpProcedimiento & "Tipo:" & strdbg & vbCrLf & vbTab
dumpProcedimiento = dumpProcedimiento & "Scope: " & IIf(Scope = "", "----------", Scope) & _
vbTab & "Categoria: " & IIf(Category = "", "----------", Category)
dumpProcedimiento = dumpProcedimiento & vbCrLf & vbTab
dumpProcedimiento = dumpProcedimiento & "Argumentos: " & IIf(ArgumentDescriptions = "", "----------", ArgumentDescriptions) & _
vbCrLf & vbTab & "Returns: " & IIf(Returns = "", "----------", Returns)
' Nuevos atributos
If Example <> "" Then
dumpProcedimiento = dumpProcedimiento & vbCrLf & vbTab & "Ejemplo: " & Example
End If
If Raises <> "" Then
dumpProcedimiento = dumpProcedimiento & vbCrLf & vbTab & "Raises: " & Raises
End If
If Dependencies <> "" Then
dumpProcedimiento = dumpProcedimiento & vbCrLf & vbTab & "Dependencies: " & Dependencies
End If
End Function