linked-data-python 0.0.3__py3-none-any.whl → 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. ldpy/__init__.py +35 -11
  2. ldpy/__main__.py +75 -250
  3. ldpy/build.py +91 -0
  4. ldpy/console.py +116 -0
  5. ldpy/debug.py +235 -0
  6. ldpy/formatter.py +329 -0
  7. ldpy/importer.py +110 -0
  8. ldpy/lsp/__init__.py +11 -0
  9. ldpy/lsp/__main__.py +4 -0
  10. ldpy/lsp/backend.py +118 -0
  11. ldpy/lsp/rpc.py +104 -0
  12. ldpy/lsp/server.py +353 -0
  13. ldpy/lsp/translate.py +140 -0
  14. ldpy/pygments_lexer.py +613 -0
  15. ldpy/runtime.py +931 -0
  16. ldpy/sparql.py +551 -0
  17. ldpy/transpiler/__init__.py +14 -0
  18. ldpy/transpiler/core.py +2558 -0
  19. ldpy/transpiler/errors.py +38 -0
  20. ldpy/transpiler/linemap.py +292 -0
  21. linked_data_python-0.2.0.dist-info/METADATA +158 -0
  22. linked_data_python-0.2.0.dist-info/RECORD +26 -0
  23. {linked_data_python-0.0.3.dist-info → linked_data_python-0.2.0.dist-info}/WHEEL +1 -1
  24. linked_data_python-0.2.0.dist-info/entry_points.txt +9 -0
  25. {linked_data_python-0.0.3.dist-info → linked_data_python-0.2.0.dist-info/licenses}/LICENSE.md +0 -0
  26. {linked_data_python-0.0.3.dist-info → linked_data_python-0.2.0.dist-info}/top_level.txt +0 -0
  27. ldpy/grun/lib.py +0 -63
  28. ldpy/grun/util.py +0 -11
  29. ldpy/ldpy.py +0 -183
  30. ldpy/rewriter/IndentedStringWriter.py +0 -54
  31. ldpy/rewriter/LDPythonRewriter.py +0 -677
  32. ldpy/rewriter/MultiChannelTokenStream.py +0 -127
  33. ldpy/rewriter/Result.py +0 -49
  34. ldpy/rewriter/__init__.py +0 -7
  35. ldpy/rewriter/antlr/LDPythonLexer.py +0 -870
  36. ldpy/rewriter/antlr/LDPythonParser.py +0 -9336
  37. ldpy/rewriter/antlr/LDPythonVisitor.py +0 -573
  38. ldpy/sparql/builtin.py +0 -326
  39. linked_data_python-0.0.3.dist-info/METADATA +0 -139
  40. linked_data_python-0.0.3.dist-info/RECORD +0 -20
  41. linked_data_python-0.0.3.dist-info/entry_points.txt +0 -3
@@ -1,677 +0,0 @@
1
- #
2
- # The MIT License (MIT)
3
- #
4
- # Copyright (c) 2022 by Maxime Lefrançois
5
- #
6
- # Permission is hereby granted, free of charge, to any person
7
- # obtaining a copy of this software and associated documentation
8
- # files (the "Software"), to deal in the Software without
9
- # restriction, including without limitation the rights to use,
10
- # copy, modify, merge, publish, distribute, sublicense, and/or sell
11
- # copies of the Software, and to permit persons to whom the
12
- # Software is furnished to do so, subject to the following
13
- # conditions:
14
- #
15
- # The above copyright notice and this permission notice shall be
16
- # included in all copies or substantial portions of the Software.
17
- #
18
- # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
19
- # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
20
- # OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
21
- # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
22
- # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
23
- # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
24
- # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
25
- # OTHER DEALINGS IN THE SOFTWARE.
26
- #
27
- # Project : ldpython-parser; Linked-Data Python to Python/Micropython Rewriter
28
- # https://gitlab.com/coswot/linked-data-python/ldpy
29
- # Developed by : Maxime Lefrançois, maxime.lefrancois@emse.fr
30
- #
31
- import secrets
32
- import rdflib
33
- from antlr4 import TerminalNode, Token, ParserRuleContext
34
- from ldpy.rewriter.antlr.LDPythonVisitor import LDPythonVisitor
35
- from ldpy.rewriter.antlr.LDPythonParser import LDPythonParser
36
- from ldpy.rewriter.IndentedStringWriter import IndentedStringWriter
37
- from ldpy.rewriter.Result import Result
38
-
39
- SIZE = 3
40
-
41
- # This class defines a complete generic visitor for a parse tree produced by LDPythonParser.
42
- class LDPythonRewriter(LDPythonVisitor):
43
-
44
- def __init__(self, output:IndentedStringWriter=IndentedStringWriter(), namespaces = {}):
45
- self.namespaces = namespaces
46
- self.output = output
47
- self.linemap = {} # store correspondence between input line and output line
48
-
49
- def write(self, s:str, ctx:ParserRuleContext, nl=True):
50
- self.output.write(s, nl)
51
- if s:
52
- self.linemap[self.output.line] = ctx.start.line
53
-
54
- def visit(self, tree):
55
- return tree.accept(self)
56
-
57
- def visitChildren(self, node, asarray=False):
58
- n = node.getChildCount()
59
- if n==1:
60
- return node.getChild(0).accept(self)
61
- result = Result()
62
- out = []
63
- for i in range(n):
64
- child = node.getChild(i)
65
- if isinstance(child, LDPythonParser.SuiteContext):
66
- raise SyntaxError("line not to be used when suite!")
67
- childResult = child.accept(self)
68
- out.append(childResult.out)
69
- result.stmts += childResult.stmts
70
- result.post_stmts += childResult.post_stmts
71
- if asarray:
72
- result.out = out
73
- else:
74
- result.out = ' '.join(out)
75
- return result
76
-
77
- def visitTerminal(self, node):
78
- return Result(node.getText())
79
-
80
- # Visit a parse tree produced by LDPythonParser#single_input.
81
- def visitSingle_input(self, ctx:LDPythonParser.Single_inputContext) -> None:
82
- if isinstance(ctx.getChild(0), TerminalNode):
83
- self.write("", ctx)
84
- return
85
- ctx.getChild(0).accept(self)
86
- if ctx.getChildCount()>1 and isinstance(ctx.getChild(0), TerminalNode):
87
- self.write("", ctx)
88
-
89
-
90
- # Visit a parse tree produced by LDPythonParser#file_input.
91
- def visitFile_input(self, ctx:LDPythonParser.File_inputContext) -> None:
92
- n = ctx.getChildCount()
93
- for i in range(n-1): # ignore the last token which is <EOF>
94
- child = ctx.getChild(i)
95
- if isinstance(child, TerminalNode):
96
- pass
97
- # self.write("", ctx)
98
- else:
99
- child.accept(self)
100
- # self.write("", ctx)
101
-
102
-
103
- # Visit a parse tree produced by LDPythonParser#eval_input.
104
- def visitEval_input(self, ctx:LDPythonParser.Eval_inputContext) -> None:
105
- raise Exception("not implemented yet")
106
-
107
-
108
- # Visit a parse tree produced by LDPythonParser#decorators.
109
- def visitDecorators(self, ctx:LDPythonParser.DecoratorsContext):
110
- result = Result()
111
- result.out = []
112
- for decorator in ctx.decorator():
113
- decoratorResult = decorator.accept(self)
114
- result.out.append(decoratorResult.out)
115
- result.stmts += decoratorResult.stmts
116
- return result
117
-
118
-
119
- # Visit a parse tree produced by LDPythonParser#decorated.
120
- def visitDecorated(self, ctx:LDPythonParser.DecoratedContext):
121
- result_decorators = ctx.decorators().accept(self)
122
- for stmt in result_decorators.stmts:
123
- self.write(stmt, ctx)
124
- ctx.getChild(1).decorators = result_decorators.out
125
- ctx.getChild(1).accept(self)
126
-
127
-
128
- # Visit a parse tree produced by LDPythonParser#base_stmt.
129
- def visitBase_stmt(self, ctx:LDPythonParser.Base_stmtContext) -> None:
130
- base = ctx.getChild(1).getText()[1:-1]
131
- self.write(f"__base__ = \"{base}\"", ctx)
132
-
133
-
134
-
135
- # Visit a parse tree produced by LDPythonParser#prefix_stmt.
136
- def visitPrefix_stmt(self, ctx:LDPythonParser.Prefix_stmtContext) -> None:
137
- prefix = ctx.NAME().getText() if ctx.NAME() else ""
138
- uri = ctx.IRIREF().getText()[1:-1]
139
- self.namespaces[prefix] = rdflib.Namespace(uri)
140
- self.write(f"__namespaces__['{prefix}'] = rdflib.Namespace('{uri}')", ctx)
141
-
142
-
143
- # Visit a parse tree produced by LDPythonParser#async_funcdef.
144
- def visitAsync_funcdef(self, ctx:LDPythonParser.Async_funcdefContext):
145
- funcdef = ctx.funcdef()
146
- funcdef.isasync = True
147
- if hasattr(ctx, "decorators"):
148
- funcdef.decorators = ctx.decorators
149
- funcdef.accept(self)
150
-
151
-
152
- # Visit a parse tree produced by LDPythonParser#funcdef.
153
- def visitFuncdef(self, ctx:LDPythonParser.FuncdefContext):
154
- out = "async " if hasattr(ctx, "isasync") else ""
155
- result_parameters = ctx.parameters().accept(self)
156
- out += "def " + ctx.NAME().getText() + result_parameters.out
157
- if ctx.test():
158
- result_test = ctx.test().accept(self)
159
- for stmt in result_test.stmts:
160
- self.write(stmt, ctx)
161
- out += " -> " + result_test.out
162
- out += ":"
163
- if hasattr(ctx, "decorators"):
164
- for decorator in ctx.decorators:
165
- self.write(decorator, ctx)
166
- self.write(out, ctx)
167
- # WARNING: les valeurs par défaut des paramètres doivent être à l'intérieur de la fonction, pas à l'exterieur
168
- # if param = None:
169
- # param = param_default
170
- self.output.indent()
171
- for stmt in result_parameters.post_stmts:
172
- self.write(stmt, ctx)
173
- self.output.dedent()
174
- ctx.suite().accept(self)
175
-
176
-
177
- # Visit a parse tree produced by LDPythonParser#typedargslist.
178
- def visitTypedargslist(self, ctx:LDPythonParser.TypedargslistContext):
179
- n = ctx.getChildCount()
180
- result = Result()
181
- out = []
182
- i=0
183
- # check if a test has stmts. make them post_stmts and delete '='
184
- while i<n:
185
- child = ctx.getChild(i)
186
- if isinstance(child, LDPythonParser.TfpdefContext):
187
- childResult = child.accept(self)
188
- out.append(childResult.out)
189
- name = childResult.out.split(":")[0]
190
- result.stmts += childResult.stmts
191
- elif isinstance(child, TerminalNode) and ( child.getText() == '*' or child.getText() == '**') :
192
- star = child.getText()
193
- i+=1
194
- child = ctx.getChild(i)
195
- childResult = child.accept(self)
196
- out.append(star + childResult.out)
197
- name = childResult.out.split(":")[0]
198
- result.stmts += childResult.stmts
199
- elif isinstance(child, TerminalNode) and child.getText() == '=':
200
- child_testResult = ctx.getChild(i+1).accept(self)
201
- # if child_testResult.stmts:
202
- if True:
203
- secret = "param_" + secrets.token_hex(SIZE)
204
- result.post_stmts.append(f"if {name} == '{secret}':")
205
- for stmt in child_testResult.stmts:
206
- result.post_stmts.append(f" {stmt}")
207
- result.post_stmts.append(f" {name} = {child_testResult.out}")
208
- out[-1] += f"= '{secret}'"
209
- i += 2
210
- # else:
211
- # out[-1] += '=' + child_testResult.out
212
- i += 1
213
- result.out = ', '.join(out)
214
- return result
215
-
216
-
217
- # Visit a parse tree produced by LDPythonParser#simple_stmt.
218
- def visitSimple_stmt(self, ctx:LDPythonParser.Simple_stmtContext) -> None:
219
- # transforms small_stmt into simple_stmt
220
- out = ''
221
- stmts = 0
222
- for small_stmt in ctx.small_stmt():
223
- childResult = small_stmt.accept(self) # type: Result
224
- if childResult.stmts:
225
- if stmts !=0:
226
- self.write(out, ctx)
227
- out = ''
228
- stmts = 0
229
- for stmt in childResult.stmts:
230
- self.write(stmt, ctx)
231
- self.write(childResult.out, ctx)
232
- else:
233
- if stmts !=0:
234
- out += '; '
235
- out += childResult.out
236
- stmts += 1
237
- if stmts !=0:
238
- self.write(out, ctx)
239
- # self.output.write("") # NEWLINE
240
-
241
-
242
- # Visit a parse tree produced by LDPythonParser#del_stmt.
243
- def visitDel_stmt(self, ctx:LDPythonParser.Del_stmtContext):
244
- childResult = ctx.exprlist().accept(self)
245
- result = Result('del ' + childResult.out)
246
- result.stmts = childResult.stmts
247
- return result
248
-
249
-
250
- # Visit a parse tree produced by LDPythonParser#return_stmt.
251
- def visitReturn_stmt(self, ctx:LDPythonParser.Return_stmtContext):
252
- if not ctx.testlist():
253
- return Result("return")
254
- childResult = ctx.testlist().accept(self)
255
- result = Result('return ' + childResult.out)
256
- result.stmts = childResult.stmts
257
- return result
258
-
259
-
260
- # Visit a parse tree produced by LDPythonParser#raise_stmt.
261
- def visitRaise_stmt(self, ctx:LDPythonParser.Raise_stmtContext):
262
- result = ctx.test()[0].accept(self)
263
- result.out = 'raise ' + result.out
264
- if len(ctx.test()>1):
265
- result2 = ctx.test()[1].accept(self)
266
- result.out += ' from ' + result2.out
267
- result.stmts += result2.stmts
268
- return result
269
-
270
-
271
- # Visit a parse tree produced by LDPythonParser#import_name.
272
- def visitImport_name(self, ctx:LDPythonParser.Import_nameContext):
273
- return Result("import " + ctx.dotted_as_names().accept(self).out)
274
-
275
-
276
- # Visit a parse tree produced by LDPythonParser#import_from.
277
- def visitImport_from(self, ctx:LDPythonParser.Import_fromContext):
278
- return Result(' '.join([ c.accept(self).out for c in ctx.getChildren() ]))
279
-
280
-
281
- # Visit a parse tree produced by LDPythonParser#import_as_name.
282
- def visitImport_as_name(self, ctx:LDPythonParser.Import_as_nameContext) -> Result:
283
- return Result(' '.join([ c.getText() for c in ctx.getChildren() ]))
284
-
285
-
286
- # Visit a parse tree produced by LDPythonParser#dotted_as_name.
287
- def visitDotted_as_name(self, ctx:LDPythonParser.Dotted_as_nameContext) -> Result:
288
- result = ctx.dotted_name().accept(self)
289
- if ctx.AS():
290
- result.out += ' as ' + ctx.NAME().getText()
291
- return result
292
-
293
- # Visit a parse tree produced by LDPythonParser#import_as_names.
294
- def visitImport_as_names(self, ctx:LDPythonParser.Import_as_namesContext) -> Result:
295
- return Result(', '.join([ c.accept(self).out for c in ctx.import_as_name() ]))
296
-
297
-
298
- # Visit a parse tree produced by LDPythonParser#dotted_as_names.
299
- def visitDotted_as_names(self, ctx:LDPythonParser.Dotted_as_namesContext) -> Result:
300
- return Result(', '.join([ c.accept(self).out for c in ctx.dotted_as_name() ]))
301
-
302
-
303
- # Visit a parse tree produced by LDPythonParser#dotted_name.
304
- def visitDotted_name(self, ctx:LDPythonParser.Dotted_nameContext) -> Result:
305
- return Result('.'.join([ c.getText() for c in ctx.NAME() ]))
306
-
307
-
308
- # Visit a parse tree produced by LDPythonParser#global_stmt.
309
- def visitGlobal_stmt(self, ctx:LDPythonParser.Global_stmtContext) -> Result:
310
- return Result('global ' + ', '.join([ c.getText() for c in ctx.NAME() ]))
311
-
312
-
313
- # Visit a parse tree produced by LDPythonParser#nonlocal_stmt.
314
- def visitNonlocal_stmt(self, ctx:LDPythonParser.Nonlocal_stmtContext) -> Result:
315
- return Result('nonlocal ' + ', '.join([ c.getText() for c in ctx.NAME() ]))
316
-
317
-
318
- # Visit a parse tree produced by LDPythonParser#async_stmt.
319
- def visitAsync_stmt(self, ctx:LDPythonParser.Async_stmtContext):
320
- child = ctx.getChild(1)
321
- child.isasync = True
322
- child.accept(self)
323
-
324
-
325
- # Visit a parse tree produced by LDPythonParser#if_stmt.
326
- def visitIf_stmt(self, ctx:LDPythonParser.If_stmtContext):
327
- stmts = []
328
- # the if test
329
- result_if = ctx.test()[0].accept(self)
330
- stmts += result_if.stmts
331
- # the elifs tests
332
- results_elif = [c.accept(self) for c in ctx.test()[1:]]
333
- for result_elif in results_elif:
334
- stmts += result_elif.stmts
335
- # print the stmts
336
- for stmt in stmts:
337
- self.write(stmt, ctx)
338
- # the if
339
- self.write("if " + result_if.out + ":", ctx)
340
- ctx.suite()[0].accept(self)
341
- # the elifs
342
- for i in range(len(results_elif)):
343
- self.write("elif " + results_elif[i].out + ":", ctx)
344
- ctx.suite()[i+1].accept(self)
345
- # the else
346
- if ctx.ELSE():
347
- self.write("else:", ctx)
348
- ctx.suite()[-1].accept(self)
349
-
350
-
351
- # Visit a parse tree produced by LDPythonParser#while_stmt.
352
- def visitWhile_stmt(self, ctx:LDPythonParser.While_stmtContext):
353
- result_test = ctx.test().accept(self)
354
- for stmt in result_test.stmts:
355
- self.write(stmt, ctx)
356
- self.write("while " + result_test.out + ":", ctx)
357
- ctx.suite()[0].accept(self)
358
- if len(ctx.suite())>1:
359
- self.write("else:", ctx)
360
- ctx.suite()[1].accept(self)
361
-
362
-
363
- # Visit a parse tree produced by LDPythonParser#for_stmt.
364
- def visitFor_stmt(self, ctx:LDPythonParser.For_stmtContext):
365
- out = "async " if hasattr(ctx, "isasync") else ""
366
- exprlist = ctx.exprlist().accept(self)
367
- for stmt in exprlist.stmts:
368
- self.write(stmt, ctx)
369
- testlist = ctx.testlist().accept(self)
370
- for stmt in testlist.stmts:
371
- self.write(stmt, ctx)
372
- out += "for " + exprlist.out + " in " + testlist.out + ":"
373
- self.write(out, ctx)
374
- ctx.suite()[0].accept(self)
375
- if len(ctx.suite())>1:
376
- self.write("else:", ctx)
377
- ctx.suite()[1].accept(self)
378
-
379
-
380
- # Visit a parse tree produced by LDPythonParser#try_stmt.
381
- def visitTry_stmt(self, ctx:LDPythonParser.Try_stmtContext):
382
- results_except_clause = [c.accept(self) for c in ctx.except_clause()]
383
- for result_except_clause in results_except_clause:
384
- for stmt in result_except_clause.stmts:
385
- self.write(stmt, ctx)
386
- self.write("try:", ctx)
387
- ctx.suite()[0].accept(self)
388
- n = len(results_except_clause)
389
- for i in range(n):
390
- self.write(results_except_clause[i].out + ":", ctx)
391
- ctx.suite()[i+1].accept(self)
392
- for i in range(ctx.getChildCount()-7,ctx.getChildCount()):
393
- if ctx.getChild(i) == ctx.ELSE():
394
- self.write("else:", ctx)
395
- ctx.getChild(i+2).accept(self)
396
- elif ctx.getChild(i) == ctx.FINALLY():
397
- self.write("finally:", ctx)
398
- ctx.getChild(i+2).accept(self)
399
-
400
-
401
- # Visit a parse tree produced by LDPythonParser#with_stmt.
402
- def visitWith_stmt(self, ctx:LDPythonParser.With_stmtContext):
403
- out = "async " if hasattr(ctx, "isasync") else ""
404
- results_with_item = [c.accept(self) for c in ctx.with_item()]
405
- results_with_item_out = [r.out for r in results_with_item]
406
- for result_with_item in results_with_item:
407
- for stmt in result_with_item.stmts:
408
- self.write(stmt, ctx)
409
- out += "with " + ",".join(results_with_item_out) + ":"
410
- self.write(out, ctx)
411
- ctx.suite().accept(self)
412
-
413
-
414
- # Visit a parse tree produced by LDPythonParser#suite.
415
- def visitSuite(self, ctx:LDPythonParser.SuiteContext):
416
- self.output.indent()
417
- if ctx.simple_stmt():
418
- ctx.simple_stmt.accept(self)
419
- for stmt in ctx.stmt():
420
- stmt.accept(self)
421
- self.output.dedent()
422
-
423
-
424
- # Visit a parse tree produced by LDPythonParser#classdef.
425
- def visitClassdef(self, ctx:LDPythonParser.ClassdefContext):
426
- out = []
427
- n = ctx.getChildCount()
428
- for i in range(n-1):
429
- childResult = ctx.getChild(i).accept(self)
430
- out.append(childResult.out)
431
- for stmt in childResult.stmts:
432
- self.write(stmt, ctx)
433
- if hasattr(ctx, "decorators"):
434
- for decorator in ctx.decorators:
435
- self.write(decorator, ctx)
436
- self.write(' '.join(out), ctx)
437
- ctx.suite().accept(self)
438
-
439
-
440
- # Visit a parse tree produced by LDPythonParser#construct_template.
441
- def visitConstruct_template(self, ctx:LDPythonParser.Construct_templateContext):
442
- rdfgraph = "graph_" + secrets.token_hex(SIZE)
443
- result = Result(rdfgraph)
444
- result.stmts.append(f"{rdfgraph} = rdflib.Graph(base=__base__)")
445
-
446
- for prefix, uri in self.namespaces.items():
447
- result.stmts.append(f"{rdfgraph}.namespace_manager.bind('{prefix}', '{uri}')")
448
-
449
- if ctx.construct_triples():
450
- childResult = ctx.construct_triples().accept(self)
451
- for stmt in childResult.stmts:
452
- if isinstance(stmt, str):
453
- result.stmts.append(stmt)
454
- elif isinstance(stmt, tuple):
455
- result.stmts.append(f"{rdfgraph}.add(({stmt[0]},{stmt[1]},{stmt[2]}))")
456
-
457
- return result
458
-
459
- # Visit a parse tree produced by LDPythonParser#construct_triples.
460
- def visitConstruct_triples(self, ctx:LDPythonParser.Construct_triplesContext):
461
- result = Result()
462
-
463
- childResult = ctx.triples_same_subject().accept(self)
464
- result.add_stmts(childResult)
465
-
466
- if ctx.construct_triples():
467
- childResult = ctx.construct_triples().accept(self)
468
- result.add_stmts(childResult)
469
-
470
- return result
471
-
472
-
473
- # Visit a parse tree produced by LDPythonParser#triples_same_subject.
474
- def visitTriples_same_subject(self, ctx:LDPythonParser.Triples_same_subjectContext):
475
- result = Result()
476
-
477
- subjectResult = ctx.getChild(0).accept(self)
478
- subject = subjectResult.out
479
- result.add_stmts(subjectResult)
480
-
481
- predicateObjectResult = ctx.getChild(1).accept(self)
482
- result.add_stmts(predicateObjectResult, subject)
483
-
484
- return result
485
-
486
-
487
- # Visit a parse tree produced by LDPythonParser#property_list.
488
- def visitProperty_list(self, ctx:LDPythonParser.Property_listContext):
489
- if ctx.property_list_not_empty():
490
- return ctx.property_list_not_empty().accept(self)
491
- else:
492
- return Result()
493
-
494
-
495
- # Visit a parse tree produced by LDPythonParser#property_list_not_empty.
496
- def visitProperty_list_not_empty(self, ctx:LDPythonParser.Property_list_not_emptyContext):
497
- result = Result()
498
- i = 0
499
- n = ctx.getChildCount()
500
- while i < n:
501
- if isinstance(ctx.getChild(i), LDPythonParser.VerbContext):
502
- verbResult = ctx.getChild(i).accept(self)
503
- verb = verbResult.out
504
- result.add_stmts(verbResult)
505
- i += 1
506
- object_listResult = ctx.getChild(i).accept(self)
507
- result.add_stmts(object_listResult, verb)
508
- i += 1
509
- return result
510
-
511
-
512
- # Visit a parse tree produced by LDPythonParser#verb.
513
- def visitVerb(self, ctx:LDPythonParser.VerbContext):
514
- if isinstance(ctx.getChild(0), TerminalNode):
515
- return Result("rdflib.RDF.type")
516
- else:
517
- return ctx.getChild(0).accept(self)
518
-
519
-
520
- # Visit a parse tree produced by LDPythonParser#object_list.
521
- def visitObject_list(self, ctx:LDPythonParser.Object_listContext):
522
- result = Result()
523
- for child in ctx.object_():
524
- childResult = child.accept(self)
525
- result.add_stmts(childResult)
526
- result.stmts.append((childResult.out,))
527
- return result
528
-
529
-
530
- # Visit a parse tree produced by LDPythonParser#blank_node_property_list.
531
- def visitBlank_node_property_list(self, ctx:LDPythonParser.Blank_node_property_listContext):
532
- rdfsubject = "bn_" + secrets.token_hex(SIZE)
533
- result = Result(rdfsubject)
534
- result.stmts.append(f"{rdfsubject} = rdflib.BNode()")
535
- childResult = ctx.property_list_not_empty().accept(self)
536
- for stmt in childResult.stmts:
537
- if isinstance(stmt, tuple) and len(stmt)<3:
538
- result.stmts.append((rdfsubject, *stmt))
539
- else:
540
- result.stmts.append(stmt)
541
- return result
542
-
543
-
544
- # Visit a parse tree produced by LDPythonParser#collection.
545
- def visitCollection(self, ctx:LDPythonParser.CollectionContext):
546
- secret = secrets.token_hex(SIZE)
547
- i = 0
548
- rdflist = f"list_{secret}_{i}"
549
- result = Result(rdflist)
550
- result.stmts.append(f"{rdflist} = rdflib.BNode()")
551
- n = len(ctx.graph_node())
552
- while i < n:
553
- rdflist = f"list_{secret}_{i}"
554
- childResult = ctx.graph_node()[i].accept(self)
555
- result.add_stmts(childResult)
556
- result.stmts.append((rdflist, "rdflib.RDF.first", childResult.out))
557
- if i < n-1:
558
- rdfrest = f"list_{secret}_{i+1}"
559
- result.stmts.append(f"{rdfrest} = rdflib.BNode()")
560
- result.stmts.append((rdflist, "rdflib.RDF.rest", rdfrest))
561
- else:
562
- result.stmts.append((rdflist, "rdflib.RDF.rest", "rdflib.RDF.nil"))
563
- i += 1
564
- return result
565
-
566
-
567
- # Visit a parse tree produced by LDPythonParser#var.
568
- def visitVar(self, ctx:LDPythonParser.VarContext):
569
- if ctx.VAR1() or ctx.VAR2():
570
- varName = ctx.getText()[1:]
571
- return Result(f"rdflib.Variable('{varName}')")
572
- return ctx.getChild(0).accept(self)
573
-
574
-
575
- # Visit a parse tree produced by LDPythonParser#graph_term.
576
- def visitGraph_term(self, ctx:LDPythonParser.Graph_termContext):
577
- if ctx.NUMBER() or ctx.TRUE() or ctx.FALSE():
578
- return Result(f"rdflib.Literal({ctx.getChild(0).getText()})")
579
- return ctx.getChild(0).accept(self)
580
-
581
-
582
- # Visit a parse tree produced by LDPythonParser#rdf_literal.
583
- def visitRdf_literal(self, ctx:LDPythonParser.Rdf_literalContext):
584
- string = ctx.STRING().getText()
585
- # if not ctx.iri() and not ctx.LANGTAG():
586
- # return Result(string)
587
- if ctx.iri():
588
- datatype = ctx.iri().accept(self)
589
- return Result(f"rdflib.Literal({string},datatype={datatype})")
590
- if ctx.firi() or ctx.fnode():
591
- datatype = ctx.getChild(2).accept(self)
592
- result = Result(f"rdflib.Literal({string},datatype={datatype})")
593
- result.add_stmts(datatype)
594
- return result
595
- elif ctx.LANGTAG():
596
- lang = ctx.LANGTAG().getText()[1:]
597
- return Result(f"rdflib.Literal({string},lang='{lang}')")
598
- else:
599
- return Result(f"rdflib.Literal({string})")
600
-
601
-
602
- # Visit a parse tree produced by LDPythonParser#iri.
603
- def visitIri(self, ctx:LDPythonParser.IriContext):
604
- if ctx.IRIREF():
605
- uri = ctx.getText()[1:-1]
606
- return Result(f"rdflib.URIRef('{uri}', __base__)")
607
- else:
608
- return ctx.prefixed_name().accept(self)
609
-
610
- # Visit a parse tree produced by LDPythonParser#prefixed_name.
611
- def visitPrefixed_name(self, ctx:LDPythonParser.Prefixed_nameContext):
612
- prefix , localName = ctx.getText().split(":", 1)
613
- if prefix not in set(self.namespaces):
614
- offendingToken : Token = ctx.start
615
- line = offendingToken.line
616
- column = offendingToken.column
617
- raise SyntaxError(f"line {line}:{column}: prefix '{prefix}:' is not defined")
618
- uri = self.namespaces[prefix][localName]
619
- return Result(f"rdflib.URIRef('{uri}', __base__)")
620
-
621
-
622
- # Visit a parse tree produced by LDPythonParser#blank_node.
623
- def visitBlank_node(self, ctx:LDPythonParser.Blank_nodeContext):
624
- name = "bn_" + secrets.token_hex(SIZE)
625
- result = Result(name)
626
- if ctx.BLANK_NODE_LABEL():
627
- label = ctx.getText()[2:]
628
- result.stmts.append(f"{name} = rdflib.BNode('{label}')")
629
- else:
630
- result.stmts.append(f"{name} = rdflib.BNode()")
631
-
632
- return result
633
-
634
-
635
- # Visit a parse tree produced by LDPythonParser#nil.
636
- def visitNil(self, ctx:LDPythonParser.NilContext):
637
- return Result("rdflib.RDF.nil")
638
-
639
-
640
- # Visit a parse tree produced by LDPythonParser#anon.
641
- def visitAnon(self, ctx:LDPythonParser.AnonContext):
642
- name = "bn_" + secrets.token_hex(SIZE)
643
- result = Result(name)
644
- result.stmts.append(f"{name} = rdflib.BNode()")
645
- return result
646
-
647
-
648
- # Visit a parse tree produced by LDPythonParser#firi.
649
- def visitFiri(self, ctx:LDPythonParser.FiriContext):
650
- name = "var_" + secrets.token_hex(SIZE)
651
- result = Result(name)
652
- out = []
653
- string = ctx.FIRIREF_START().getText()[2:-1]
654
- if len(string)>0:
655
- out.append(f"'{string}'")
656
- n = ctx.getChildCount()
657
- for i in range(1,n,2):
658
- testResult = ctx.getChild(i).accept(self)
659
- result.add_stmts(testResult)
660
- out.append("str(" + testResult.out + ")")
661
- string = ctx.getChild(i+1).accept(self).out[1:-1]
662
- if len(string)>0:
663
- out.append(f"'{string}'")
664
- iri = ' + '.join(out)
665
- result.stmts.append(f"{name} = rdflib.URIRef({iri})")
666
- return result
667
-
668
- # Visit a parse tree produced by LDPythonParser#fnode.
669
- def visitFnode(self, ctx:LDPythonParser.FnodeContext):
670
- testResult = ctx.test().accept(self)
671
- if not testResult.stmts:
672
- return testResult
673
- name = "var_" + secrets.token_hex(SIZE)
674
- result = Result(name)
675
- result.add_stmts(testResult)
676
- result.stmts.append(f"{name} = {testResult.out}")
677
- return result