1 /*******************************************************************************
2 * Copyright (c) 2010 Association for Decentralized Information Management in
4 * All rights reserved. This program and the accompanying materials
5 * are made available under the terms of the Eclipse Public License v1.0
6 * which accompanies this distribution, and is available at
7 * http://www.eclipse.org/legal/epl-v10.html
10 * VTT Technical Research Centre of Finland - initial API and implementation
11 *******************************************************************************/
12 package org.simantics.databoard.units.internal.parser;
14 import org.simantics.databoard.units.internal.UnitParseException;
16 public abstract class UnitParser {
29 if(pos >= string.length())
32 nextChar = string.charAt(pos);
35 public void unit(String string, int sign) throws UnitParseException {
47 * unit_expression: unit_numerator [ "/" unit_denominator ]
48 * unit_numerator: "1" | unit_factors | "(" unit_expression ")"
49 * unit_denominator: unit_factor | "(" unit_expression ")"
50 * unit_factors: unit_factor [ "." unit_factors ]
51 * unit_factor: unit_operand [ unit_exponent ]
52 * unit_exponent: [ "+" | "-" ] integer
53 * unit_operand: unit_symbol | unit_prefix unit_symbol
56 void expression() throws UnitParseException {
64 void numerator() throws UnitParseException {
67 else if(nextChar == '(') {
76 void denominator() throws UnitParseException {
88 void factors() throws UnitParseException {
98 void factor() throws UnitParseException {
100 int factorBegin = pos;
101 while((nextChar >= 'a' && nextChar <= 'z') || (nextChar >= 'A' && nextChar <= 'Z') || (nextChar=='ยต') || nextChar=='(' || nextChar==')' || nextChar=='%')
103 int exponentBegin = pos;
104 if(factorBegin == exponentBegin)
105 throw new UnitParseException(string,
106 "Expected base unit name, but got " + charName(nextChar) + " at position " + pos + ".");
107 String baseUnit = string.substring(factorBegin, exponentBegin);
110 if(nextChar == '-' || nextChar == '+' || (nextChar >= '0' && nextChar <= '9')) {
112 while(nextChar >= '0' && nextChar <= '9')
115 int exponentEnd = pos;
116 if(exponentEnd > exponentBegin) {
117 String exponentString = string.substring(exponentBegin, exponentEnd);
119 visit(baseUnit, sign * Integer.parseInt(exponentString));
120 } catch(NumberFormatException e) {
121 throw new UnitParseException(string,
122 "Invalid exponent \"" + exponentString + "\" at position " + pos + ".");
126 visit(baseUnit, sign);
129 private void skip(char c) throws UnitParseException {
134 private static String charName(int c) {
136 return "'" + Character.toString((char)c) + "'";
138 return "end of unit";
141 private void expect(int c) throws UnitParseException {
143 throw new UnitParseException(string,
144 "Expected " + charName(c) + ", but got " + charName(nextChar) + " at position " + pos + ".");
147 public abstract void visit(String baseUnit, int exponent);