我有一个tokenizer,我需要提取每个标记,并将其写入输出文件。令牌必须以某种逻辑顺序存在(根据语言语法)。因此,我还必须验证令牌顺序遵循语法规范。 目前,我正在通过使用类似于assert的方法来执行此操作,该方法会使用适当的消息抛出异常。 这是代码:
public void compileVarDec() throws IOException, IllegalSyntaxException {
output.write("<varDec>\n");
verifyStaticField();
output.write("<keyword> " + tokenizer.keyWord() + " </keyword>\n");
tokenizer.advance();
verifyLegalType();
output.write("<keyword> " + tokenizer.keyWord() + " </keyword>\n");
tokenizer.advance();
verifyIdentifier();
output.write("<identifier> " + tokenizer.identifier() + " </identifier>\n");
tokenizer.advance();
verifySymbol(JackTokenizer.SEMI_COLON);
output.write("<symbol> " + tokenizer.symbol() + " </symbol>\n");
tokenizer.advance();
output.write("</varDec>\n");
}
private void verifySymbol(char token) throws IllegalSyntaxException {
if (tokenizer.tokenType() != JackTokenizer.TOKEN_TYPE.SYMBOL ||
tokenizer.symbol() != token)
throw new IllegalSyntaxException("Expected the symbol '" + token + "'");
}
private void verifyStaticField() throws IllegalSyntaxException {
if (tokenizer.tokenType() != JackTokenizer.TOKEN_TYPE.KEYWORD ||
(!tokenizer.keyWord().equals(JackTokenizer.FIELD) &&
!tokenizer.keyWord().equals(JackTokenizer.STATIC))) {
throw new IllegalSyntaxException("Expected 'static' or 'field'");
}
}
private void verifyLegalType() throws IllegalSyntaxException {
if (tokenizer.tokenType() != JackTokenizer.TOKEN_TYPE.KEYWORD ||
(!tokenizer.keyWord().equals(JackTokenizer.INT) &&
!tokenizer.keyWord().equals(JackTokenizer.CHAR) &&
!tokenizer.keyWord().equals(JackTokenizer.BOOLEAN)))
throw new IllegalSyntaxException("Expected a legal type");
}
private void verifyIdentifier() throws IllegalSyntaxException {
if (tokenizer.tokenType() != JackTokenizer.TOKEN_TYPE.IDENTIFIER)
throw new IllegalSyntaxException("Expected an identifier");
}
以这种方式验证输入是否被视为良好做法?要调用一个检查输入的方法,然后,如果它无效,将抛出异常,当前方法将忽略抛出的异常并将其传递给它? 如果您有其他建议我会很高兴听到。注意,我想避免两次运行令牌,所以我必须验证输入并同时写入输出