com.davidbracewell.parsing.handlers.CommentHandler.java Source code

Java tutorial

Introduction

Here is the source code for com.davidbracewell.parsing.handlers.CommentHandler.java

Source

/*
 * (c) 2005 David B. Bracewell
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

package com.davidbracewell.parsing.handlers;

import com.davidbracewell.parsing.ParseException;
import com.davidbracewell.parsing.Parser;
import com.davidbracewell.parsing.ParserToken;
import com.davidbracewell.parsing.ParserTokenType;
import com.davidbracewell.parsing.expressions.CommentExpression;
import com.davidbracewell.parsing.expressions.Expression;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.collect.Iterables;

import javax.annotation.Nullable;
import java.util.List;

/**
 * @author David B. Bracewell
 */
public class CommentHandler extends PrefixHandler {

    private final ParserTokenType endOfLine;

    public CommentHandler(ParserTokenType endOfLine) {
        super(0);
        this.endOfLine = endOfLine;
    }

    @Override
    public Expression parse(Parser parser, ParserToken token) throws ParseException {
        List<ParserToken> tokens = parser.tokenStream().consumeUntil(endOfLine);
        if (parser.tokenStream().lookAheadType(0) != null) {
            parser.tokenStream().consume(endOfLine);
        }
        return new CommentExpression(token.type,
                token.text + Joiner.on("").join(Iterables.transform(tokens, new Function<ParserToken, String>() {
                    @Nullable
                    @Override
                    public String apply(ParserToken input) {
                        return input == null ? null : input.text;
                    }
                })));
    }

}//END OF CommentHandler