@param text Text to visit. @return Parse result wrapper of generated AST.
(String text)
| 41 | * @return Parse result wrapper of generated AST. |
| 42 | */ |
| 43 | public static ParseResult<RootAST> parse(String text) { |
| 44 | List<ASTParseException> problems = new ArrayList<>(); |
| 45 | RootAST root = new RootAST(); |
| 46 | int lineNo = 0; |
| 47 | String[] lines = text.split("[\n\r]"); |
| 48 | // Collect aliases |
| 49 | List<AliasAST> aliases = new ArrayList<>(); |
| 50 | for(String line : lines) { |
| 51 | lineNo++; |
| 52 | // Skip empty lines |
| 53 | if(line.trim().isEmpty()) |
| 54 | continue; |
| 55 | // Check for alias |
| 56 | String token = line.trim().split("\\s")[0].toUpperCase(); |
| 57 | try { |
| 58 | if (token.equals("ALIAS")) { |
| 59 | // Why? Because we want to support aliases-in-aliases when they |
| 60 | // are defined in order. |
| 61 | String lineCopy = line; |
| 62 | for (AliasAST alias : aliases) |
| 63 | lineCopy = lineCopy.replace("${" + alias.getName().getName() + "}", |
| 64 | alias.getValue().getValue()); |
| 65 | // Parse alias |
| 66 | aliases.add((AliasAST) getParser(lineNo, token).visit(lineNo, lineCopy)); |
| 67 | } |
| 68 | } catch(ClassCastException | ASTParseException ex) { |
| 69 | /* ignored, we will collect the error on the second pass */ |
| 70 | } |
| 71 | } |
| 72 | // Parse again |
| 73 | lineNo = 0; |
| 74 | for(String line : lines) { |
| 75 | lineNo++; |
| 76 | // Skip empty lines |
| 77 | String trim = line.trim(); |
| 78 | if(trim.isEmpty()) |
| 79 | continue; |
| 80 | // Determine parse action from starting token |
| 81 | String token = trim.split("\\s")[0].toUpperCase(); |
| 82 | try { |
| 83 | AbstractParser parser = getParser(lineNo, token); |
| 84 | if(parser == null) |
| 85 | throw new ASTParseException(lineNo, "Unknown identifier: " + token); |
| 86 | // Apply aliases |
| 87 | String lineCopy = line; |
| 88 | for (AliasAST alias : aliases) |
| 89 | lineCopy = lineCopy.replace("${" + alias.getName().getName() + "}", |
| 90 | alias.getValue().getValue()); |
| 91 | // Parse and add to root |
| 92 | AST ast = parser.visit(lineNo, lineCopy); |
| 93 | root.addChild(ast); |
| 94 | } catch(ASTParseException ex) { |
| 95 | problems.add(ex); |
| 96 | } |
| 97 | } |
| 98 | return new ParseResult<>(root, problems); |
| 99 | } |
| 100 |