001package org.hl7.fhir.utilities;
002
003import java.util.ArrayList;
004import java.util.List;
005
006public class SemverParser {
007  private final String input;
008  private int pos;
009  private final List<String> parts;
010  private final boolean allowWildcards;
011  private final boolean requirePatch;
012
013  public SemverParser(String input) {
014    this(input, false, true);
015  }
016
017  public SemverParser(String input, boolean allowWildcards) {
018    this(input, allowWildcards, true);
019  }
020
021  public SemverParser(String input, boolean allowWildcards, boolean requirePatch) {
022    this.input = input;
023    this.pos = 0;
024    this.parts = new ArrayList<>();
025    this.allowWildcards = allowWildcards;
026    this.requirePatch = requirePatch;
027  }
028
029  public static class ParseResult {
030    private final List<String> parts;
031    private final String error;
032
033    private ParseResult(List<String> parts, String error) {
034      this.parts = parts;
035      this.error = error;
036    }
037
038    public static ParseResult success(List<String> parts) {
039      return new ParseResult(new ArrayList<>(parts), null);
040    }
041
042    public static ParseResult error(String error) {
043      return new ParseResult(null, error);
044    }
045
046    public boolean isSuccess() {
047      return error == null;
048    }
049
050    public List<String> getParts() {
051      return parts;
052    }
053
054    public String getError() {
055      return error;
056    }
057
058    // Semantic accessor methods
059    public String getMajor() {
060      if (!isSuccess() || parts.isEmpty()) {
061        return null;
062      }
063      return parts.get(0);
064    }
065
066    public String getMinor() {
067      if (!isSuccess() || parts.size() < 3) {
068        return null;
069      }
070      // parts[0]=major, parts[1]=".", parts[2]=minor
071      return parts.get(2);
072    }
073
074    public String getPatch() {
075      if (!isSuccess() || parts.size() < 5) {
076        return null;
077      }
078      // Check if we actually have a patch: parts[0]=major, parts[1]=".", parts[2]=minor, parts[3]=".", parts[4]=patch
079      // If parts[3] is not ".", then there's no patch (e.g., "1.2-alpha" has "-" at parts[3])
080      if (!".".equals(parts.get(3))) {
081        return null;
082      }
083      return parts.get(4);
084    }
085
086    public String getReleaseLabel() {
087      if (!isSuccess()) {
088        return null;
089      }
090
091      // Find the "-" separator
092      int dashIndex = -1;
093      for (int i = 0; i < parts.size(); i++) {
094        if ("-".equals(parts.get(i))) {
095          dashIndex = i;
096          break;
097        }
098      }
099
100      if (dashIndex == -1) {
101        return null; // No pre-release
102      }
103
104      // Find the "+" separator (if any)
105      int plusIndex = parts.size(); // Default to end of parts
106      for (int i = dashIndex + 1; i < parts.size(); i++) {
107        if ("+".equals(parts.get(i))) {
108          plusIndex = i;
109          break;
110        }
111      }
112
113      // Reconstruct the release label from parts between "-" and "+"
114      StringBuilder sb = new StringBuilder();
115      for (int i = dashIndex + 1; i < plusIndex; i++) {
116        sb.append(parts.get(i));
117      }
118
119      return sb.length() > 0 ? sb.toString() : null;
120    }
121
122    public String getBuild() {
123      if (!isSuccess()) {
124        return null;
125      }
126
127      // Find the "+" separator
128      int plusIndex = -1;
129      for (int i = 0; i < parts.size(); i++) {
130        if ("+".equals(parts.get(i))) {
131          plusIndex = i;
132          break;
133        }
134      }
135
136      if (plusIndex == -1) {
137        return null; // No build metadata
138      }
139
140      // Reconstruct the build metadata from parts after "+"
141      StringBuilder sb = new StringBuilder();
142      for (int i = plusIndex + 1; i < parts.size(); i++) {
143        sb.append(parts.get(i));
144      }
145
146      return sb.length() > 0 ? sb.toString() : null;
147    }
148  }
149
150  public ParseResult parse() {
151    try {
152      parseValidSemver();
153      if (pos != input.length()) {
154        throw new IllegalArgumentException(
155          String.format("Unexpected characters at position %d: \"%s\"", pos, input.substring(pos))
156        );
157      }
158      return ParseResult.success(parts);
159    } catch (Exception e) {
160      return ParseResult.error(e.getMessage());
161    }
162  }
163
164  // <valid semver> ::= <version core> | <version core> "-" <pre-release> | <version core> "+" <build> | <version core> "-" <pre-release> "+" <build>
165  private void parseValidSemver() {
166    parseVersionCore();
167
168    if (peek() != null && peek() == '-') {
169      consume('-');
170      parts.add("-");
171      parsePreRelease();
172
173      if (peek() != null && peek() == '+') {
174        consume('+');
175        parts.add("+");
176        parseBuild();
177      }
178    } else if (peek() != null && peek() == '+') {
179      consume('+');
180      parts.add("+");
181      parseBuild();
182    }
183  }
184
185  // <version core> ::= <major> "." <minor> "." <patch>
186  // With wildcards: <major> | <major> "." <wildcard> | <major> "." <minor> "." <wildcard>
187  // With optional patch: <major> "." <minor> | <major> "." <minor> "." <patch>
188  private void parseVersionCore() {
189    String major = parseNumericIdentifier();
190    parts.add(major);
191
192    // Must have at least a dot after major
193    if (peek() == null || peek() != '.') {
194      throw new IllegalArgumentException(String.format("Expected '.' after major version at position %d", pos));
195    }
196
197    consume('.');
198    parts.add(".");
199
200    boolean hasWildcardInMinor = false;
201
202    // Parse minor version (either numeric or wildcard)
203    if (allowWildcards && isWildcard(peek())) {
204      String wildcard = parseWildcard();
205      parts.add(wildcard);
206      hasWildcardInMinor = true;
207    } else {
208      String minor = parseNumericIdentifier();
209      parts.add(minor);
210    }
211
212    // If we have a wildcard in minor, we can stop here or continue with wildcards only
213    if (hasWildcardInMinor) {
214      // Check if we have a dot for patch
215      if (peek() != null && peek() == '.') {
216        consume('.');
217        parts.add(".");
218
219        // After wildcard, only wildcards are allowed in version positions
220        if (allowWildcards && isWildcard(peek())) {
221          String patchWildcard = parseWildcard();
222          parts.add(patchWildcard);
223        } else {
224          throw new IllegalArgumentException(String.format("After wildcard in version, only wildcards are allowed at position %d", pos));
225        }
226      }
227      // Otherwise, we're done with version core - this handles "1.*" case
228      return;
229    }
230
231    // Check if patch is optional and we're at end or at a separator
232    if (!requirePatch && (peek() == null || peek() == '-' || peek() == '+')) {
233      return; // Valid to stop here when patch is optional
234    }
235
236    // Must have a dot after minor (either for patch or error)
237    if (peek() == null || peek() != '.') {
238      if (requirePatch) {
239        throw new IllegalArgumentException(String.format("Expected '.' after minor version at position %d", pos));
240      } else {
241        return; // Optional patch not provided
242      }
243    }
244
245    consume('.');
246    parts.add(".");
247
248    // Parse patch version (either numeric or wildcard)
249    if (allowWildcards && isWildcard(peek())) {
250      String wildcard = parseWildcard();
251      parts.add(wildcard);
252    } else {
253      String patch = parseNumericIdentifier();
254      parts.add(patch);
255    }
256  }
257
258  // <pre-release> ::= <dot-separated pre-release identifiers>
259  private void parsePreRelease() {
260    parseDotSeparatedPreReleaseIdentifiers();
261  }
262
263  // <dot-separated pre-release identifiers> ::= <pre-release identifier> | <pre-release identifier> "." <dot-separated pre-release identifiers>
264  private void parseDotSeparatedPreReleaseIdentifiers() {
265    String identifier = parsePreReleaseIdentifier();
266    parts.add(identifier);
267
268    while (peek() != null && peek() == '.' && pos + 1 < input.length() && input.charAt(pos + 1) != '+') {
269      consume('.');
270      parts.add(".");
271      String nextIdentifier = parsePreReleaseIdentifier();
272      parts.add(nextIdentifier);
273    }
274  }
275
276  // <build> ::= <dot-separated build identifiers>
277  private void parseBuild() {
278    parseDotSeparatedBuildIdentifiers();
279  }
280
281  // <dot-separated build identifiers> ::= <build identifier> | <build identifier> "." <dot-separated build identifiers>
282  private void parseDotSeparatedBuildIdentifiers() {
283    String identifier = parseBuildIdentifier();
284    parts.add(identifier);
285
286    while (peek() != null && peek() == '.') {
287      consume('.');
288      parts.add(".");
289      String nextIdentifier = parseBuildIdentifier();
290      parts.add(nextIdentifier);
291    }
292  }
293
294  // <pre-release identifier> ::= <alphanumeric identifier> | <numeric identifier>
295  private String parsePreReleaseIdentifier() {
296    // Check if this is a wildcard first
297    if (allowWildcards && isWildcard(peek())) {
298      return parseWildcard();
299    }
300
301    // Check if this is a valid numeric identifier by looking ahead
302    if (isValidNumericIdentifier()) {
303      return parseNumericIdentifier();
304    }
305
306    // Must be alphanumeric identifier
307    return parseAlphanumericIdentifier();
308  }
309
310  // <build identifier> ::= <alphanumeric identifier> | <digits>
311  private String parseBuildIdentifier() {
312    // Check if this is a wildcard first
313    if (allowWildcards && isWildcard(peek())) {
314      return parseWildcard();
315    }
316
317    // Check if this is pure digits by looking ahead
318    if (isValidDigitsOnly()) {
319      return parseDigits();
320    }
321
322    // Must be alphanumeric identifier
323    return parseAlphanumericIdentifier();
324  }
325
326  // <numeric identifier> ::= "0" | <positive digit> | <positive digit> <digits>
327  private String parseNumericIdentifier() {
328    int start = pos;
329
330    if (peek() != null && peek() == '0') {
331      consume('0');
332      return "0";
333    }
334
335    if (isPositiveDigit(peek())) {
336      consumePositiveDigit();
337      parseOptionalDigits();
338      return input.substring(start, pos);
339    }
340
341    throw new IllegalArgumentException(String.format("Expected numeric identifier at position %d", pos));
342  }
343
344  // <alphanumeric identifier> ::= <non-digit> | <non-digit> <identifier characters> | <identifier characters> <non-digit> | <identifier characters> <non-digit> <identifier characters>
345  private String parseAlphanumericIdentifier() {
346    int start = pos;
347    boolean hasNonDigit = false;
348
349    if (pos >= input.length()) {
350      throw new IllegalArgumentException(String.format("Expected alphanumeric identifier at position %d", pos));
351    }
352
353    // Must have at least one character
354    if (isNonDigit(peek())) {
355      hasNonDigit = true;
356      consumeNonDigit();
357    } else if (isDigit(peek())) {
358      consumeDigit();
359    } else {
360      throw new IllegalArgumentException(String.format("Expected alphanumeric identifier at position %d", pos));
361    }
362
363    // Continue with identifier characters
364    while (isIdentifierCharacter(peek())) {
365      if (isNonDigit(peek())) {
366        hasNonDigit = true;
367        consumeNonDigit();
368      } else {
369        consumeDigit();
370      }
371    }
372
373    if (!hasNonDigit) {
374      throw new IllegalArgumentException(String.format("Alphanumeric identifier must contain at least one non-digit at position %d", start));
375    }
376
377    return input.substring(start, pos);
378  }
379
380  // <digits> ::= <digit> | <digit> <digits>
381  private String parseDigits() {
382    int start = pos;
383
384    if (!isDigit(peek())) {
385      throw new IllegalArgumentException(String.format("Expected digit at position %d", pos));
386    }
387
388    consumeDigit();
389    parseOptionalDigits();
390
391    return input.substring(start, pos);
392  }
393
394  private void parseOptionalDigits() {
395    while (isDigit(peek())) {
396      consumeDigit();
397    }
398  }
399
400  // Helper methods
401  private Character peek() {
402    return pos < input.length() ? input.charAt(pos) : null;
403  }
404
405  private void consume(char expected) {
406    Character actual = peek();
407    if (actual == null || actual != expected) {
408      throw new IllegalArgumentException(String.format("Expected '%c' at position %d, got '%s'", expected, pos, actual == null ? "end of input" : actual));
409    }
410    pos++;
411  }
412
413  private boolean isPositiveDigit(Character ch) {
414    return ch != null && ch >= '1' && ch <= '9';
415  }
416
417  private boolean isDigit(Character ch) {
418    return ch != null && ch >= '0' && ch <= '9';
419  }
420
421  private boolean isLetter(Character ch) {
422    return ch != null && ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z'));
423  }
424
425  private boolean isNonDigit(Character ch) {
426    return isLetter(ch) || (ch != null && ch == '-');
427  }
428
429  private boolean isIdentifierCharacter(Character ch) {
430    return isDigit(ch) || isNonDigit(ch);
431  }
432
433  private void consumePositiveDigit() {
434    if (!isPositiveDigit(peek())) {
435      throw new IllegalArgumentException(String.format("Expected positive digit at position %d", pos));
436    }
437    pos++;
438  }
439
440  private void consumeDigit() {
441    if (!isDigit(peek())) {
442      throw new IllegalArgumentException(String.format("Expected digit at position %d", pos));
443    }
444    pos++;
445  }
446
447  private void consumeNonDigit() {
448    if (!isNonDigit(peek())) {
449      throw new IllegalArgumentException(String.format("Expected non-digit at position %d", pos));
450    }
451    pos++;
452  }
453
454  private boolean isValidDigitsOnly() {
455    if (pos >= input.length() || !isDigit(input.charAt(pos))) {
456      return false;
457    }
458
459    int tempPos = pos;
460    // Advance through all digits
461    while (tempPos < input.length() && isDigit(input.charAt(tempPos))) {
462      tempPos++;
463    }
464
465    // Check if this sequence contains ONLY digits (no non-digits)
466    // and is followed by a separator or end
467    return (tempPos >= input.length()) ||
468      input.charAt(tempPos) == '.' ||
469      input.charAt(tempPos) == '+' ||
470      !isIdentifierCharacter(input.charAt(tempPos));
471  }
472
473  private boolean isValidNumericIdentifier() {
474    if (pos >= input.length()) {
475      return false;
476    }
477
478    // Case 1: exactly "0"
479    if (input.charAt(pos) == '0') {
480      // Check if it's followed by a non-identifier character or end of string
481      return (pos + 1 >= input.length()) ||
482        !isIdentifierCharacter(input.charAt(pos + 1)) ||
483        input.charAt(pos + 1) == '.' ||
484        input.charAt(pos + 1) == '+';
485    }
486
487    // Case 2: positive digit followed by only digits
488    if (isPositiveDigit(input.charAt(pos))) {
489      int tempPos = pos + 1;
490      while (tempPos < input.length() && isDigit(input.charAt(tempPos))) {
491        tempPos++;
492      }
493      // Must be followed by non-identifier character, dot, plus, or end
494      return (tempPos >= input.length()) ||
495        !isIdentifierCharacter(input.charAt(tempPos)) ||
496        input.charAt(tempPos) == '.' ||
497        input.charAt(tempPos) == '+';
498    }
499
500    return false;
501  }
502
503  private boolean isNumericIdentifierStart() {
504    Character ch = peek();
505    return ch != null && (ch == '0' || isPositiveDigit(ch));
506  }
507
508  private boolean isAlphanumericIdentifierStart() {
509    // An alphanumeric identifier can start with any identifier character,
510    // but we need to look ahead to see if it will contain a non-digit
511    boolean hasNonDigit = false;
512    int tempPos = pos;
513
514    // Look ahead to see if this could be an alphanumeric identifier
515    while (tempPos < input.length() && isIdentifierCharacter(input.charAt(tempPos))) {
516      if (isNonDigit(input.charAt(tempPos))) {
517        hasNonDigit = true;
518      }
519      tempPos++;
520      // Stop at separators
521      if (tempPos < input.length() && (input.charAt(tempPos) == '.' || input.charAt(tempPos) == '+')) {
522        break;
523      }
524    }
525
526    return hasNonDigit && isIdentifierCharacter(peek());
527  }
528
529  // Wildcard support methods
530  private boolean isWildcard(Character ch) {
531    return ch != null && (ch == 'x' || ch == 'X' || ch == '*');
532  }
533
534  private String parseWildcard() {
535    int start = pos;
536
537    // Parse one or more wildcard characters
538    while (isWildcard(peek())) {
539      pos++;
540    }
541
542    if (start == pos) {
543      throw new IllegalArgumentException(String.format("Expected wildcard at position %d", pos));
544    }
545
546    return input.substring(start, pos);
547  }
548
549  // Static convenience method
550  public static ParseResult parseSemver(String input) {
551    SemverParser parser = new SemverParser(input);
552    return parser.parse();
553  }
554
555  public static ParseResult parseSemver(String input, boolean allowWildcards) {
556    SemverParser parser = new SemverParser(input, allowWildcards);
557    return parser.parse();
558  }
559
560  public static ParseResult parseSemver(String input, boolean allowWildcards, boolean requirePatch) {
561    SemverParser parser = new SemverParser(input, allowWildcards, requirePatch);
562    return parser.parse();
563  }
564}