001/*
002 * Anarres C Preprocessor
003 * Copyright (c) 2007-2015, Shevek
004 *
005 * Licensed under the Apache License, Version 2.0 (the "License");
006 * you may not use this file except in compliance with the License.
007 * You may obtain a copy of the License at
008 *
009 *     http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
014 * or implied.  See the License for the specific language governing
015 * permissions and limitations under the License.
016 */
017package org.anarres.cpp;
018
019import java.io.BufferedReader;
020import java.io.File;
021import java.io.FileInputStream;
022import java.io.FileReader;
023import java.io.IOException;
024import java.nio.charset.Charset;
025import javax.annotation.Nonnull;
026
027/**
028 * A {@link Source} which lexes a file.
029 *
030 * The input is buffered.
031 *
032 * @see Source
033 */
034public class FileLexerSource extends InputLexerSource {
035
036    private final String path;
037    private final File file;
038
039    /**
040     * Creates a new Source for lexing the given File.
041     *
042     * Preprocessor directives are honoured within the file.
043     */
044    public FileLexerSource(@Nonnull File file, @Nonnull Charset charset, @Nonnull String path)
045            throws IOException {
046        super(new FileInputStream(file), charset);
047        this.file = file;
048        this.path = path;
049    }
050
051    public FileLexerSource(@Nonnull File file, @Nonnull String path)
052            throws IOException {
053        this(file, Charset.defaultCharset(), path);
054    }
055
056    public FileLexerSource(@Nonnull File file, @Nonnull Charset charset)
057            throws IOException {
058        this(file, charset, file.getPath());
059    }
060
061    @Deprecated
062    public FileLexerSource(@Nonnull File file)
063            throws IOException {
064        this(file, Charset.defaultCharset());
065    }
066
067    public FileLexerSource(@Nonnull String path, @Nonnull Charset charset)
068            throws IOException {
069        this(new File(path), charset, path);
070    }
071
072    @Deprecated
073    public FileLexerSource(@Nonnull String path)
074            throws IOException {
075        this(path, Charset.defaultCharset());
076    }
077
078    @Nonnull
079    public File getFile() {
080        return file;
081    }
082
083    /**
084     * This is not necessarily the same as getFile().getPath() in case we are in a chroot.
085     */
086    @Override
087    public String getPath() {
088        return path;
089    }
090
091    @Override
092    public String getName() {
093        return getPath();
094    }
095
096    @Override
097    public String toString() {
098        return "file " + getPath();
099    }
100}