/*
* Copyright (C) Chaperon. All rights reserved.
* -------------------------------------------------------------------------
* This software is published under the terms of the Apache Software License
* version 1.1, a copy of which has been included with this distribution in
* the LICENSE file.
*/
package net.sourceforge.chaperon.build;
import net.sourceforge.chaperon.model.Violations;
import net.sourceforge.chaperon.model.lexicon.Lexeme;
import net.sourceforge.chaperon.model.lexicon.Lexicon;
import net.sourceforge.chaperon.process.LexicalAutomaton;
import net.sourceforge.chaperon.process.PatternAutomaton;
import org.apache.commons.logging.Log;
/**
* This class represents a builder for the lexical automata.
*
* @author <a href="mailto:stephan@apache.org">Stephan Michels </a>
* @version CVS $Id: LexicalAutomatonBuilder.java,v 1.7 2003/12/09 19:55:52 benedikta Exp $
*/
public class LexicalAutomatonBuilder
{
private Lexicon lexicon = null;
private LexicalAutomaton automaton = null;
private Log log = null;
/**
* Create a builder for an lexical automaton.
*
* @param lexicon Lexicon, which should be used for the automaton.
*/
public LexicalAutomatonBuilder(Lexicon lexicon)
{
this(lexicon, null);
}
/**
* Create a builder for an lexical automaton.
*
* @param lexicon Lexicon, which should be used for the automaton.
* @param log Log, which should be used.
*/
public LexicalAutomatonBuilder(Lexicon lexicon, Log log)
{
this.log = log;
try
{
this.lexicon = (Lexicon)lexicon.clone();
}
catch (CloneNotSupportedException cnse)
{
throw new IllegalArgumentException("Lexicon is nor cloneable");
}
Violations violations = lexicon.validate();
if ((violations!=null) && (violations.getViolationCount()>0))
throw new IllegalArgumentException("Lexicon is not valid: "+violations.getViolation(0));
LexicalAutomaton automaton = new LexicalAutomaton(lexicon.getLexemeCount());
Lexeme lexeme;
PatternAutomaton definition = null;
for (int i = 0; i<lexicon.getLexemeCount(); i++)
{
lexeme = lexicon.getLexeme(i);
automaton.setLexemeSymbol(i, (lexeme.getSymbol()!=null) ? lexeme.getSymbol().getName() : null);
definition = (new PatternAutomatonBuilder(lexeme.getDefinition())).getPatternAutomaton();
if (definition!=null)
automaton.setLexemeDefinition(i, definition);
else
throw new IllegalArgumentException("Couldn't create PatternAutomaton for "+
lexeme.getSymbol()+" of \""+lexeme.getDefinition()+"\"");
}
this.automaton = automaton;
}
/**
* Return the builded automaton. This method will return null, if an error occurs.
*
* @return Lexical automaton.
*/
public LexicalAutomaton getLexicalAutomaton()
{
return automaton;
}
}