Search in sources :

Example 1 with Nullable

use of org.antlr.v4.runtime.misc.Nullable in project grakn by graknlabs.

the class QueryParserImpl method parseList.

/**
 * @param reader a reader representing several queries
 * @return a list of queries
 */
@Override
public <T extends Query<?>> Stream<T> parseList(Reader reader) {
    UnbufferedCharStream charStream = new UnbufferedCharStream(reader);
    GraqlErrorListener errorListener = GraqlErrorListener.withoutQueryString();
    GraqlLexer lexer = createLexer(charStream, errorListener);
    /*
            We tell the lexer to copy the text into each generated token.
            Normally when calling `Token#getText`, it will look into the underlying `TokenStream` and call
            `TokenStream#size` to check it is in-bounds. However, `UnbufferedTokenStream#size` is not supported
            (because then it would have to read the entire input). To avoid this issue, we set this flag which will
            copy over the text into each `Token`, s.t. that `Token#getText` will just look up the copied text field.
        */
    lexer.setTokenFactory(new CommonTokenFactory(true));
    // Use an unbuffered token stream so we can handle extremely large input strings
    UnbufferedTokenStream tokenStream = new UnbufferedTokenStream(ChannelTokenSource.of(lexer));
    GraqlParser parser = createParser(tokenStream, errorListener);
    /*
            The "bail" error strategy prevents us reading all the way to the end of the input, e.g.

            ```
            match $x isa person; insert $x has name "Bob"; match $x isa movie; get;
                                                           ^
            ```

            In this example, when ANTLR reaches the indicated `match`, it considers two possibilities:

            1. this is the end of the query
            2. the user has made a mistake. Maybe they accidentally pasted the `match` here.

            Because of case 2, ANTLR will parse beyond the `match` in order to produce a more helpful error message.
            This causes memory issues for very large queries, so we use the simpler "bail" strategy that will
            immediately stop when it hits `match`.
        */
    parser.setErrorHandler(new BailErrorStrategy());
    // This is a lazy iterator that will only consume a single query at a time, without parsing any further.
    // This means it can pass arbitrarily long streams of queries in constant memory!
    Iterable<T> queryIterator = () -> new AbstractIterator<T>() {

        @Nullable
        @Override
        protected T computeNext() {
            int latestToken = tokenStream.LA(1);
            if (latestToken == Token.EOF) {
                endOfData();
                return null;
            } else {
                // When we next run it, it will start where it left off in the stream
                return (T) QUERY.parse(parser, errorListener);
            }
        }
    };
    return StreamSupport.stream(queryIterator.spliterator(), false);
}
Also used : CommonTokenFactory(org.antlr.v4.runtime.CommonTokenFactory) GraqlParser(ai.grakn.graql.internal.antlr.GraqlParser) BailErrorStrategy(org.antlr.v4.runtime.BailErrorStrategy) UnbufferedCharStream(org.antlr.v4.runtime.UnbufferedCharStream) AbstractIterator(com.google.common.collect.AbstractIterator) UnbufferedTokenStream(org.antlr.v4.runtime.UnbufferedTokenStream) GraqlLexer(ai.grakn.graql.internal.antlr.GraqlLexer)

Example 2 with Nullable

use of org.antlr.v4.runtime.misc.Nullable in project java by wavefrontHQ.

the class ReportPointIngesterFormatter method drive.

@Override
public ReportPoint drive(String input, String defaultHostName, String customerId, @Nullable List<String> customSourceTags) {
    Queue<Token> queue = getQueue(input);
    ReportPoint point = new ReportPoint();
    point.setTable(customerId);
    // if the point has a timestamp, this would be overriden
    point.setTimestamp(Clock.now());
    AbstractWrapper wrapper = new ReportPointWrapper(point);
    try {
        for (FormatterElement element : elements) {
            element.consume(queue, wrapper);
        }
    } catch (Exception ex) {
        throw new RuntimeException("Could not parse: " + input, ex);
    }
    if (!queue.isEmpty()) {
        throw new RuntimeException("Could not parse: " + input);
    }
    // Delta metrics cannot have negative values
    if ((point.getMetric().startsWith(DELTA_PREFIX) || point.getMetric().startsWith(DELTA_PREFIX_2)) && point.getValue() instanceof Number) {
        double v = ((Number) point.getValue()).doubleValue();
        if (v <= 0) {
            throw new RuntimeException("Delta metrics cannot be non-positive: " + input);
        }
    }
    String host = null;
    Map<String, String> annotations = point.getAnnotations();
    if (annotations != null) {
        host = annotations.remove("source");
        if (host == null) {
            host = annotations.remove("host");
        } else if (annotations.containsKey("host")) {
            // we have to move this elsewhere since during querying,
            // host= would be interpreted as host and not a point tag
            annotations.put("_host", annotations.remove("host"));
        }
        if (annotations.containsKey("tag")) {
            annotations.put("_tag", annotations.remove("tag"));
        }
        if (host == null && customSourceTags != null) {
            // iterate over the set of custom tags, breaking when one is found
            for (String tag : customSourceTags) {
                host = annotations.get(tag);
                if (host != null) {
                    break;
                }
            }
        }
    }
    if (host == null) {
        host = defaultHostName;
    }
    point.setHost(host);
    return ReportPoint.newBuilder(point).build();
}
Also used : Token(org.antlr.v4.runtime.Token) ReportPoint(wavefront.report.ReportPoint)

Example 3 with Nullable

use of org.antlr.v4.runtime.misc.Nullable in project titan.EclipsePlug-ins by eclipse.

the class TitanListener method syntaxError.

@Override
public void syntaxError(@NotNull final Recognizer<?, ?> recognizer, @Nullable final Object offendingSymbol, final int line, final int charPositionInLine, @NotNull final String msg, @Nullable final RecognitionException e) {
    SyntacticErrorStorage errorStorage;
    if (offendingSymbol instanceof CommonToken) {
        final CommonToken token = (CommonToken) offendingSymbol;
        errorStorage = new SyntacticErrorStorage(line, token.getStartIndex(), token.getStopIndex() + 1, msg, e);
    } else {
        errorStorage = new SyntacticErrorStorage(line, charPositionInLine, charPositionInLine + 1, msg, e);
    }
    errorsStored.add(errorStorage);
}
Also used : CommonToken(org.antlr.v4.runtime.CommonToken)

Example 4 with Nullable

use of org.antlr.v4.runtime.misc.Nullable in project vespa by vespa-engine.

the class ProgramParser method prepareParser.

private yqlplusParser prepareParser(String programName, CharStream input) {
    yqlplusLexer lexer = new yqlplusLexer(input);
    lexer.removeErrorListeners();
    lexer.addErrorListener(new BaseErrorListener() {

        @Override
        public void syntaxError(@NotNull Recognizer<?, ?> recognizer, @Nullable Object offendingSymbol, int line, int charPositionInLine, @NotNull String msg, @Nullable RecognitionException e) {
            throw new ProgramCompileException(new Location(programName, line, charPositionInLine), msg);
        }
    });
    TokenStream tokens = new CommonTokenStream(lexer);
    yqlplusParser parser = new yqlplusParser(tokens);
    parser.removeErrorListeners();
    parser.addErrorListener(new BaseErrorListener() {

        @Override
        public void syntaxError(@NotNull Recognizer<?, ?> recognizer, @Nullable Object offendingSymbol, int line, int charPositionInLine, @NotNull String msg, @Nullable RecognitionException e) {
            throw new ProgramCompileException(new Location(programName, line, charPositionInLine), msg);
        }
    });
    parser.getInterpreter().setPredictionMode(PredictionMode.SLL);
    return parser;
}
Also used : CommonTokenStream(org.antlr.v4.runtime.CommonTokenStream) TokenStream(org.antlr.v4.runtime.TokenStream) CommonTokenStream(org.antlr.v4.runtime.CommonTokenStream) BaseErrorListener(org.antlr.v4.runtime.BaseErrorListener) RecognitionException(org.antlr.v4.runtime.RecognitionException)

Example 5 with Nullable

use of org.antlr.v4.runtime.misc.Nullable in project batfish by batfish.

the class Batfish method blacklistInterface.

/**
 * Helper function to disable a blacklisted interface and update the given {@link
 * ValidateEnvironmentAnswerElement} if the interface does not actually exist.
 */
private static void blacklistInterface(Map<String, Configuration> configurations, ValidateEnvironmentAnswerElement veae, NodeInterfacePair iface) {
    String hostname = iface.getHostname();
    String ifaceName = iface.getInterface();
    @Nullable Configuration node = configurations.get(hostname);
    if (node == null) {
        veae.setValid(false);
        veae.getUndefinedInterfaceBlacklistNodes().add(hostname);
        return;
    }
    @Nullable Interface nodeIface = node.getInterfaces().get(ifaceName);
    if (nodeIface == null) {
        veae.setValid(false);
        veae.getUndefinedInterfaceBlacklistInterfaces().computeIfAbsent(hostname, k -> new TreeSet<>()).add(ifaceName);
        return;
    }
    nodeIface.setActive(false);
    nodeIface.setBlacklisted(true);
}
Also used : JuniperFlattener(org.batfish.grammar.juniper.JuniperFlattener) TreeMultiSet(org.batfish.datamodel.collections.TreeMultiSet) BfConsts(org.batfish.common.BfConsts) HeaderQuestion(org.batfish.datamodel.questions.smt.HeaderQuestion) Topology(org.batfish.datamodel.Topology) Map(java.util.Map) RoutesByVrf(org.batfish.datamodel.collections.RoutesByVrf) Pair(org.batfish.common.Pair) Path(java.nio.file.Path) TopologyExtractor(org.batfish.grammar.topology.TopologyExtractor) ConfigurationFormat(org.batfish.datamodel.ConfigurationFormat) GenericConfigObject(org.batfish.datamodel.GenericConfigObject) AnswerSummary(org.batfish.datamodel.answers.AnswerSummary) ReachabilityQuerySynthesizer(org.batfish.z3.ReachabilityQuerySynthesizer) AssertionCombinedParser(org.batfish.grammar.assertion.AssertionCombinedParser) ParseEnvironmentBgpTableJob(org.batfish.job.ParseEnvironmentBgpTableJob) Serializable(java.io.Serializable) Environment(org.batfish.datamodel.pojo.Environment) AssertionExtractor(org.batfish.grammar.assertion.AssertionExtractor) Stream(java.util.stream.Stream) NamedStructureEquivalenceSets(org.batfish.datamodel.collections.NamedStructureEquivalenceSets) RoleQuestion(org.batfish.datamodel.questions.smt.RoleQuestion) BatfishCompressor(org.batfish.symbolic.abstraction.BatfishCompressor) CoordConsts(org.batfish.common.CoordConsts) AssertionContext(org.batfish.grammar.assertion.AssertionParser.AssertionContext) BatfishStackTrace(org.batfish.common.BatfishException.BatfishStackTrace) AnswerElement(org.batfish.datamodel.answers.AnswerElement) JuniperCombinedParser(org.batfish.grammar.juniper.JuniperCombinedParser) ExceptionUtils(org.apache.commons.lang3.exception.ExceptionUtils) InitInfoAnswerElement(org.batfish.datamodel.answers.InitInfoAnswerElement) QuerySynthesizer(org.batfish.z3.QuerySynthesizer) NodJob(org.batfish.z3.NodJob) RipNeighbor(org.batfish.datamodel.RipNeighbor) SerializationUtils(org.apache.commons.lang3.SerializationUtils) HostConfiguration(org.batfish.representation.host.HostConfiguration) AclLine(org.batfish.z3.AclLine) DataPlanePlugin(org.batfish.common.plugin.DataPlanePlugin) ParseStatus(org.batfish.datamodel.answers.ParseStatus) Lists(com.google.common.collect.Lists) RunAnalysisAnswerElement(org.batfish.datamodel.answers.RunAnalysisAnswerElement) DeviceType(org.batfish.datamodel.DeviceType) AclReachabilityQuerySynthesizer(org.batfish.z3.AclReachabilityQuerySynthesizer) ImmutableSortedSet(com.google.common.collect.ImmutableSortedSet) Directory(org.batfish.common.Directory) ParseTreeWalker(org.antlr.v4.runtime.tree.ParseTreeWalker) IOException(java.io.IOException) InterfaceType(org.batfish.datamodel.InterfaceType) ReachabilitySettings(org.batfish.datamodel.questions.ReachabilitySettings) JSONArray(org.codehaus.jettison.json.JSONArray) NodeRoleSpecifier(org.batfish.datamodel.NodeRoleSpecifier) AnswerStatus(org.batfish.datamodel.answers.AnswerStatus) ExecutionException(java.util.concurrent.ExecutionException) ParseEnvironmentRoutingTableJob(org.batfish.job.ParseEnvironmentRoutingTableJob) BlacklistDstIpQuerySynthesizer(org.batfish.z3.BlacklistDstIpQuerySynthesizer) CleanBatfishException(org.batfish.common.CleanBatfishException) TreeMap(java.util.TreeMap) JSONException(org.codehaus.jettison.json.JSONException) Snapshot(org.batfish.common.Snapshot) IpsecVpn(org.batfish.datamodel.IpsecVpn) SortedSet(java.util.SortedSet) DataPlaneAnswerElement(org.batfish.datamodel.answers.DataPlaneAnswerElement) BiFunction(java.util.function.BiFunction) FlowTrace(org.batfish.datamodel.FlowTrace) BgpTableFormat(org.batfish.grammar.BgpTableFormat) FlowHistory(org.batfish.datamodel.FlowHistory) Edge(org.batfish.datamodel.Edge) ForwardingAnalysisImpl(org.batfish.datamodel.ForwardingAnalysisImpl) OspfProcess(org.batfish.datamodel.OspfProcess) Collectors.toMap(java.util.stream.Collectors.toMap) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) PropertyChecker(org.batfish.symbolic.smt.PropertyChecker) ConvertConfigurationAnswerElement(org.batfish.datamodel.answers.ConvertConfigurationAnswerElement) NodFirstUnsatJob(org.batfish.z3.NodFirstUnsatJob) VyosFlattener(org.batfish.grammar.vyos.VyosFlattener) Vrf(org.batfish.datamodel.Vrf) ImmutableSet(com.google.common.collect.ImmutableSet) ParseVendorConfigurationJob(org.batfish.job.ParseVendorConfigurationJob) RipProcess(org.batfish.datamodel.RipProcess) StandardReachabilityQuerySynthesizer(org.batfish.z3.StandardReachabilityQuerySynthesizer) Collection(java.util.Collection) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) InferRoles(org.batfish.role.InferRoles) AclLinesAnswerElement(org.batfish.datamodel.answers.AclLinesAnswerElement) ParseEnvironmentRoutingTablesAnswerElement(org.batfish.datamodel.answers.ParseEnvironmentRoutingTablesAnswerElement) NavigableMap(java.util.NavigableMap) Collectors(java.util.stream.Collectors) Settings(org.batfish.config.Settings) BatfishCombinedParser(org.batfish.grammar.BatfishCombinedParser) Entry(java.util.Map.Entry) BatfishJobExecutor(org.batfish.job.BatfishJobExecutor) Ip(org.batfish.datamodel.Ip) NodeInterfacePair(org.batfish.datamodel.collections.NodeInterfacePair) ForwardingAnalysis(org.batfish.datamodel.ForwardingAnalysis) BatfishException(org.batfish.common.BatfishException) IpAccessList(org.batfish.datamodel.IpAccessList) ConcurrentMap(java.util.concurrent.ConcurrentMap) HashSet(java.util.HashSet) TestrigSettings(org.batfish.config.Settings.TestrigSettings) BgpAdvertisementsByVrf(org.batfish.datamodel.collections.BgpAdvertisementsByVrf) ImmutableList(com.google.common.collect.ImmutableList) Version(org.batfish.common.Version) BatfishObjectMapper(org.batfish.common.util.BatfishObjectMapper) NamedStructureEquivalenceSet(org.batfish.datamodel.collections.NamedStructureEquivalenceSet) Configuration(org.batfish.datamodel.Configuration) ComputeDataPlaneResult(org.batfish.common.plugin.DataPlanePlugin.ComputeDataPlaneResult) ImmutableConfiguration(org.apache.commons.configuration2.ImmutableConfiguration) Nonnull(javax.annotation.Nonnull) ConvertConfigurationJob(org.batfish.job.ConvertConfigurationJob) Answerer(org.batfish.common.Answerer) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) NodAnswerElement(org.batfish.datamodel.answers.NodAnswerElement) NodFirstUnsatAnswerElement(org.batfish.datamodel.answers.NodFirstUnsatAnswerElement) InitStepAnswerElement(org.batfish.datamodel.answers.InitStepAnswerElement) NodSatAnswerElement(org.batfish.datamodel.answers.NodSatAnswerElement) ParseAnswerElement(org.batfish.datamodel.answers.ParseAnswerElement) IpAccessListLine(org.batfish.datamodel.IpAccessListLine) FileVisitOption(java.nio.file.FileVisitOption) AwsConfiguration(org.batfish.representation.aws.AwsConfiguration) Cache(com.google.common.cache.Cache) HeaderLocationQuestion(org.batfish.datamodel.questions.smt.HeaderLocationQuestion) AssertionAst(org.batfish.datamodel.assertion.AssertionAst) Interface(org.batfish.datamodel.Interface) CompositeNodJob(org.batfish.z3.CompositeNodJob) DirectoryStream(java.nio.file.DirectoryStream) Flow(org.batfish.datamodel.Flow) FlattenVendorConfigurationAnswerElement(org.batfish.datamodel.answers.FlattenVendorConfigurationAnswerElement) InvalidReachabilitySettingsException(org.batfish.datamodel.questions.InvalidReachabilitySettingsException) GrammarSettings(org.batfish.grammar.GrammarSettings) IptablesVendorConfiguration(org.batfish.representation.iptables.IptablesVendorConfiguration) Verify(com.google.common.base.Verify) DataPlane(org.batfish.datamodel.DataPlane) VendorConfiguration(org.batfish.vendor.VendorConfiguration) Set(java.util.Set) EnvironmentSettings(org.batfish.config.Settings.EnvironmentSettings) IBatfish(org.batfish.common.plugin.IBatfish) Question(org.batfish.datamodel.questions.Question) Roles(org.batfish.symbolic.abstraction.Roles) ParserRuleContext(org.antlr.v4.runtime.ParserRuleContext) ForwardingAction(org.batfish.datamodel.ForwardingAction) CommonUtil(org.batfish.common.util.CommonUtil) EarliestMoreGeneralReachableLineQuerySynthesizer(org.batfish.z3.EarliestMoreGeneralReachableLineQuerySynthesizer) AclReachabilityEntry(org.batfish.datamodel.answers.AclLinesAnswerElement.AclReachabilityEntry) PluginClientType(org.batfish.common.plugin.PluginClientType) TreeSet(java.util.TreeSet) ArrayList(java.util.ArrayList) BgpAdvertisement(org.batfish.datamodel.BgpAdvertisement) BgpTablePlugin(org.batfish.common.plugin.BgpTablePlugin) ParseTreePrettyPrinter(org.batfish.grammar.ParseTreePrettyPrinter) ReachEdgeQuerySynthesizer(org.batfish.z3.ReachEdgeQuerySynthesizer) ValidateEnvironmentAnswerElement(org.batfish.datamodel.answers.ValidateEnvironmentAnswerElement) ImmutableSortedMap(com.google.common.collect.ImmutableSortedMap) LinkedHashSet(java.util.LinkedHashSet) Nullable(javax.annotation.Nullable) BgpAdvertisementType(org.batfish.datamodel.BgpAdvertisement.BgpAdvertisementType) Files(java.nio.file.Files) JSONObject(org.codehaus.jettison.json.JSONObject) ExternalBgpAdvertisementPlugin(org.batfish.common.plugin.ExternalBgpAdvertisementPlugin) File(java.io.File) ParseEnvironmentBgpTablesAnswerElement(org.batfish.datamodel.answers.ParseEnvironmentBgpTablesAnswerElement) Paths(java.nio.file.Paths) ActiveSpan(io.opentracing.ActiveSpan) HeaderSpace(org.batfish.datamodel.HeaderSpace) SynthesizerInputImpl(org.batfish.z3.SynthesizerInputImpl) MultiSet(org.batfish.datamodel.collections.MultiSet) NodesSpecifier(org.batfish.datamodel.questions.NodesSpecifier) Answer(org.batfish.datamodel.answers.Answer) NodSatJob(org.batfish.z3.NodSatJob) FlattenVendorConfigurationJob(org.batfish.job.FlattenVendorConfigurationJob) TypeReference(com.fasterxml.jackson.core.type.TypeReference) PatternSyntaxException(java.util.regex.PatternSyntaxException) ImmutableMap(com.google.common.collect.ImmutableMap) Sets(com.google.common.collect.Sets) List(java.util.List) GNS3TopologyExtractor(org.batfish.grammar.topology.GNS3TopologyExtractor) Warnings(org.batfish.common.Warnings) Pattern(java.util.regex.Pattern) Synthesizer(org.batfish.z3.Synthesizer) PluginConsumer(org.batfish.common.plugin.PluginConsumer) SortedMap(java.util.SortedMap) MultipathInconsistencyQuerySynthesizer(org.batfish.z3.MultipathInconsistencyQuerySynthesizer) BatfishLogger(org.batfish.common.BatfishLogger) HashMap(java.util.HashMap) SimpleImmutableEntry(java.util.AbstractMap.SimpleImmutableEntry) AbstractRoute(org.batfish.datamodel.AbstractRoute) SubRange(org.batfish.datamodel.SubRange) VyosCombinedParser(org.batfish.grammar.vyos.VyosCombinedParser) Warning(org.batfish.common.Warning) Iterator(java.util.Iterator) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) GlobalTracer(io.opentracing.util.GlobalTracer) GNS3TopologyCombinedParser(org.batfish.grammar.topology.GNS3TopologyCombinedParser) ParseVendorConfigurationAnswerElement(org.batfish.datamodel.answers.ParseVendorConfigurationAnswerElement) DataPlanePluginSettings(org.batfish.common.plugin.DataPlanePluginSettings) ReportAnswerElement(org.batfish.datamodel.answers.ReportAnswerElement) Collections(java.util.Collections) HostConfiguration(org.batfish.representation.host.HostConfiguration) Configuration(org.batfish.datamodel.Configuration) ImmutableConfiguration(org.apache.commons.configuration2.ImmutableConfiguration) AwsConfiguration(org.batfish.representation.aws.AwsConfiguration) IptablesVendorConfiguration(org.batfish.representation.iptables.IptablesVendorConfiguration) VendorConfiguration(org.batfish.vendor.VendorConfiguration) TreeSet(java.util.TreeSet) Nullable(javax.annotation.Nullable) Interface(org.batfish.datamodel.Interface)

Aggregations

ParserRuleContext (org.antlr.v4.runtime.ParserRuleContext)5 Nullable (org.antlr.v4.runtime.misc.Nullable)5 Token (org.antlr.v4.runtime.Token)4 IntervalSet (org.antlr.v4.runtime.misc.IntervalSet)4 Nullable (javax.annotation.Nullable)3 ATNState (org.antlr.v4.runtime.atn.ATNState)3 BitSet (java.util.BitSet)2 HashSet (java.util.HashSet)2 ClassNode (kalang.ast.ClassNode)2 CommonToken (org.antlr.v4.runtime.CommonToken)2 NotNull (org.antlr.v4.runtime.misc.NotNull)2 GraqlLexer (ai.grakn.graql.internal.antlr.GraqlLexer)1 GraqlParser (ai.grakn.graql.internal.antlr.GraqlParser)1 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)1 TypeReference (com.fasterxml.jackson.core.type.TypeReference)1 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 Verify (com.google.common.base.Verify)1 Cache (com.google.common.cache.Cache)1 AbstractIterator (com.google.common.collect.AbstractIterator)1 ImmutableList (com.google.common.collect.ImmutableList)1