-
Notifications
You must be signed in to change notification settings - Fork 762
/
Copy pathImportSpecification.cs
80 lines (63 loc) · 2.79 KB
/
ImportSpecification.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using Bicep.Core.Diagnostics;
using Bicep.Core.Parsing;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.ServiceModel.Syndication;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace Bicep.Core.Syntax
{
public class ImportSpecification : ISymbolNameSource
{
// The setting below adds syntax highlighting for regex.
// language=regex
private const string NamePattern = "[a-zA-Z][a-zA-Z0-9]+";
// Regex copied from https://semver.org/.
// language=regex
private const string SemanticVersionPattern = @"(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?";
private static readonly Regex SpecificationPattern = new(
@$"^(?<name>{NamePattern})@(?<version>{SemanticVersionPattern})$",
RegexOptions.ECMAScript | RegexOptions.Compiled);
private ImportSpecification(string name, string version, bool isValid, TextSpan span)
{
Name = name;
Version = version;
IsValid = isValid;
Span = span;
}
public string Name { get; }
public string Version { get; }
public bool IsValid { get; }
public TextSpan Span { get; }
public static ImportSpecification From(SyntaxBase specificationSyntax)
{
switch (specificationSyntax)
{
case StringSyntax stringSyntax when stringSyntax.TryGetLiteralValue() is { } value:
var (name, version, isValid) = Parse(value);
var span = isValid ? new TextSpan(stringSyntax.Span.Position + 1, name.Length) : stringSyntax.Span;
return new ImportSpecification(name, version, isValid, span);
case SkippedTriviaSyntax trivia:
return new ImportSpecification(trivia.TriviaName, trivia.TriviaName, false, trivia.Span);
default:
return new ImportSpecification(LanguageConstants.ErrorName, LanguageConstants.ErrorName, false, specificationSyntax.Span);
}
}
private static (string Name, string Version, bool IsValid) Parse(string value)
{
var match = SpecificationPattern.Match(value);
if (!match.Success)
{
return (LanguageConstants.ErrorName, LanguageConstants.ErrorName, false);
}
var name = match.Groups["name"].Value;
var version = match.Groups["version"].Value;
return (name, version, true);
}
}
}