01: /*
02: * Copyright Aduna (http://www.aduna-software.com/) (c) 1997-2006.
03: *
04: * Licensed under the Aduna BSD-style license.
05: */
06: package org.openrdf.query.parser.serql;
07:
08: import org.openrdf.query.parser.serql.ast.ASTEdge;
09: import org.openrdf.query.parser.serql.ast.ASTNode;
10: import org.openrdf.query.parser.serql.ast.ASTNodeElem;
11: import org.openrdf.query.parser.serql.ast.ASTReifiedStat;
12: import org.openrdf.query.parser.serql.ast.ASTVar;
13: import org.openrdf.query.parser.serql.ast.SyntaxTreeBuilderTreeConstants;
14: import org.openrdf.query.parser.serql.ast.VisitorException;
15:
16: /**
17: * Inserts anonymous variables into the abstract syntax tree at places where
18: * such variables are already implicitly present.
19: */
20: public class AnonymousVarGenerator extends ASTVisitorBase {
21:
22: private int anonymousVarNo = 1;
23:
24: @Override
25: public Object visit(ASTNode node, Object data)
26: throws VisitorException {
27: if (node.jjtGetNumChildren() == 0) {
28: ASTNodeElem nodeElem = createNodeElem();
29: nodeElem.jjtSetParent(node);
30: node.jjtAppendChild(nodeElem);
31: }
32:
33: return super .visit(node, data);
34: }
35:
36: @Override
37: public Object visit(ASTReifiedStat node, Object data)
38: throws VisitorException {
39: if (node.jjtGetChild(0) instanceof ASTEdge) {
40: // subject node is missing
41: ASTNodeElem nodeElem = createNodeElem();
42: nodeElem.jjtSetParent(node);
43: node.jjtInsertChild(nodeElem, 0);
44: }
45:
46: if (node.jjtGetNumChildren() <= 2) {
47: // object node is missing
48: ASTNodeElem nodeElem = createNodeElem();
49: nodeElem.jjtSetParent(node);
50: node.jjtAppendChild(nodeElem);
51: }
52:
53: if (node.getID() == null) {
54: node.setID(createAnonymousVar());
55: }
56:
57: return super .visit(node, data);
58: }
59:
60: private ASTNodeElem createNodeElem() {
61: ASTNodeElem nodeElem = new ASTNodeElem(
62: SyntaxTreeBuilderTreeConstants.JJTNODEELEM);
63:
64: ASTVar var = createAnonymousVar();
65: var.jjtSetParent(nodeElem);
66: nodeElem.jjtAppendChild(var);
67:
68: return nodeElem;
69: }
70:
71: private ASTVar createAnonymousVar() {
72: ASTVar var = new ASTVar(SyntaxTreeBuilderTreeConstants.JJTVAR);
73: var.setName("-anon-" + anonymousVarNo++);
74: var.setAnonymous(true);
75: return var;
76: }
77: }
|