Remove preprocessor directives that check COMPACT, PORTABLE, NET40PLUS, NET45PLUS from code

This commit is contained in:
Ivan Kochurkin 2020-12-02 20:58:18 +03:00
parent 11077ac15c
commit 573f71bf7d
28 changed files with 21 additions and 871 deletions

View File

@ -3,18 +3,11 @@
* can be found in the LICENSE.txt file in the project root.
*/
#if !PORTABLE
using Antlr4.Runtime.Sharpen;
using Encoding = System.Text.Encoding;
using File = System.IO.File;
namespace Antlr4.Runtime
{
#if COMPACT
using StreamReader = System.IO.StreamReader;
#endif
/// <summary>
/// This is an
/// <see cref="AntlrInputStream"/>
@ -47,17 +40,10 @@ namespace Antlr4.Runtime
}
string text;
#if !COMPACT
if (encoding != null)
text = File.ReadAllText(fileName, encoding);
else
text = File.ReadAllText(fileName);
#else
if (encoding != null)
text = ReadAllText(fileName, encoding);
else
text = ReadAllText(fileName);
#endif
data = text.ToCharArray();
n = data.Length;
@ -70,25 +56,5 @@ namespace Antlr4.Runtime
return fileName;
}
}
#if COMPACT
private static string ReadAllText(string path)
{
using (var reader = new StreamReader(path))
{
return reader.ReadToEnd();
}
}
private static string ReadAllText(string path, Encoding encoding)
{
using (var reader = new StreamReader(path, encoding ?? Encoding.Default))
{
return reader.ReadToEnd();
}
}
#endif
}
}
#endif

View File

@ -398,7 +398,7 @@ namespace Antlr4.Runtime.Atn
}
}
protected internal virtual void ReadSets(ATN atn, IList<IntervalSet> sets, Func<int> readUnicode)
protected internal virtual void ReadSets(ATN atn, IList<IntervalSet> sets, System.Func<int> readUnicode)
{
//
// SETS

View File

@ -77,9 +77,7 @@ namespace Antlr4.Runtime.Atn
protected void ConsoleWriteLine(string format, params object[] arg)
{
#if !PORTABLE
System.Console.WriteLine(format, arg);
#endif
}
public PredictionContextCache getSharedContextCache()

View File

@ -95,9 +95,7 @@ namespace Antlr4.Runtime.Atn
{
if (epsilonOnlyTransitions != e.IsEpsilon)
{
#if !PORTABLE
System.Console.Error.WriteLine("ATN state {0} has both epsilon and non-epsilon transitions.", stateNumber);
#endif
epsilonOnlyTransitions = false;
}
}

View File

@ -2112,9 +2112,7 @@ namespace Antlr4.Runtime.Atn
*/
public void DumpDeadEndConfigs(NoViableAltException nvae)
{
#if !PORTABLE
System.Console.Error.WriteLine("dead end configs: ");
#endif
foreach (ATNConfig c in nvae.DeadEndConfigs.configs)
{
String trans = "no edges";
@ -2133,9 +2131,8 @@ namespace Antlr4.Runtime.Atn
trans = (not ? "~" : "") + "Set " + st.set.ToString();
}
}
#if !PORTABLE
System.Console.Error.WriteLine(c.ToString(parser, true) + ":" + trans);
#endif
}
}

View File

@ -437,11 +437,7 @@ namespace Antlr4.Runtime.Atn
Collections.EmptyList<PrecedencePredicate>();
List<PrecedencePredicate> result = collection.OfType<PrecedencePredicate>().ToList();
#if NET40PLUS
collection.ExceptWith(result);
#else
collection.ExceptWith(result.Cast<SemanticContext>());
#endif
return result;
}
}

View File

@ -3,10 +3,6 @@
* can be found in the LICENSE.txt file in the project root.
*/
#if !PORTABLE
using Antlr4.Runtime;
using Antlr4.Runtime.Sharpen;
using System.IO;
namespace Antlr4.Runtime
@ -44,6 +40,4 @@ namespace Antlr4.Runtime
output.WriteLine("line " + line + ":" + charPositionInLine + " " + msg);
}
}
}
#endif
}

View File

@ -160,9 +160,7 @@ namespace Antlr4.Runtime
}
else
{
#if !PORTABLE
System.Console.Error.WriteLine("unknown recognition error type: " + e.GetType().FullName);
#endif
NotifyErrorListeners(recognizer, e.Message, e);
}
}

View File

@ -4,8 +4,6 @@
*/
using System.Collections;
using System.Collections.Generic;
using Antlr4.Runtime.Dfa;
using Antlr4.Runtime.Sharpen;
namespace Antlr4.Runtime.Dfa
{
@ -78,11 +76,7 @@ namespace Antlr4.Runtime.Dfa
get;
}
#if NET45PLUS
public abstract IReadOnlyDictionary<int, T> ToMap();
#else
public abstract IDictionary<int, T> ToMap();
#endif
public virtual IEnumerator<KeyValuePair<int, T>> GetEnumerator()
{

View File

@ -5,15 +5,9 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using Antlr4.Runtime.Dfa;
using Antlr4.Runtime.Sharpen;
using Interlocked = System.Threading.Interlocked;
#if NET45PLUS
using Volatile = System.Threading.Volatile;
#elif !PORTABLE && !COMPACT
using Thread = System.Threading.Thread;
#endif
namespace Antlr4.Runtime.Dfa
{
@ -35,13 +29,7 @@ namespace Antlr4.Runtime.Dfa
{
get
{
#if NET45PLUS
return Volatile.Read(ref size);
#elif !PORTABLE && !COMPACT
return Thread.VolatileRead(ref size);
#else
return Interlocked.CompareExchange(ref size, 0, 0);
#endif
}
}
@ -67,11 +55,7 @@ namespace Antlr4.Runtime.Dfa
return null;
}
#if NET45PLUS
return Volatile.Read(ref arrayData[key - minIndex]);
#else
return Interlocked.CompareExchange(ref arrayData[key - minIndex], null, null);
#endif
}
}
@ -156,24 +140,15 @@ namespace Antlr4.Runtime.Dfa
return new EmptyEdgeMap<T>(minIndex, maxIndex);
}
#if NET45PLUS
public override IReadOnlyDictionary<int, T> ToMap()
#else
public override IDictionary<int, T> ToMap()
#endif
{
if (IsEmpty)
{
return Sharpen.Collections.EmptyMap<int, T>();
}
#if COMPACT
IDictionary<int, T> result = new SortedList<int, T>();
#elif PORTABLE && !NET45PLUS
IDictionary<int, T> result = new Dictionary<int, T>();
#else
IDictionary<int, T> result = new SortedDictionary<int, T>();
#endif
for (int i = 0; i < arrayData.Length; i++)
{
T element = arrayData[i];
@ -183,11 +158,8 @@ namespace Antlr4.Runtime.Dfa
}
result[i + minIndex] = element;
}
#if NET45PLUS
return new ReadOnlyDictionary<int, T>(result);
#else
return result;
#endif
}
}
}

View File

@ -3,11 +3,7 @@
* can be found in the LICENSE.txt file in the project root.
*/
using System.Collections.Generic;
using Antlr4.Runtime.Sharpen;
#if NET45PLUS
using System.Collections.ObjectModel;
#endif
namespace Antlr4.Runtime.Dfa
{
@ -74,18 +70,9 @@ namespace Antlr4.Runtime.Dfa
}
}
#if NET45PLUS
public override IReadOnlyDictionary<int, T> ToMap()
#else
public override IDictionary<int, T> ToMap()
#endif
{
Dictionary<int, T> result = new Dictionary<int, T>();
#if NET45PLUS
return new ReadOnlyDictionary<int, T>(result);
#else
return result;
#endif
return new ReadOnlyDictionary<int, T>(new Dictionary<int, T>());
}
}
}

View File

@ -39,12 +39,7 @@ namespace Antlr4.Runtime.Dfa
[return: NotNull]
IEdgeMap<T> Clear();
#if NET45PLUS
[return: NotNull]
IReadOnlyDictionary<int, T> ToMap();
#else
[return: NotNull]
IDictionary<int, T> ToMap();
#endif
}
}

View File

@ -3,7 +3,6 @@
* can be found in the LICENSE.txt file in the project root.
*/
using System.Collections.Generic;
using Antlr4.Runtime.Sharpen;
namespace Antlr4.Runtime.Dfa
{
@ -123,17 +122,13 @@ namespace Antlr4.Runtime.Dfa
return this;
}
#if NET45PLUS
public override IReadOnlyDictionary<int, T> ToMap()
#else
public override IDictionary<int, T> ToMap()
#endif
{
if (IsEmpty)
{
return Sharpen.Collections.EmptyMap<int, T>();
}
return Antlr4.Runtime.Sharpen.Collections.SingletonMap(key, value);
return Sharpen.Collections.SingletonMap(key, value);
}
}
}

View File

@ -181,11 +181,7 @@ namespace Antlr4.Runtime.Dfa
return new EmptyEdgeMap<T>(minIndex, maxIndex);
}
#if NET45PLUS
public override IReadOnlyDictionary<int, T> ToMap()
#else
public override IDictionary<int, T> ToMap()
#endif
{
if (IsEmpty)
{
@ -193,22 +189,14 @@ namespace Antlr4.Runtime.Dfa
}
lock (this)
{
#if COMPACT
IDictionary<int, T> result = new SortedList<int, T>();
#elif PORTABLE && !NET45PLUS
IDictionary<int, T> result = new Dictionary<int, T>();
#else
IDictionary<int, T> result = new SortedDictionary<int, T>();
#endif
for (int i = 0; i < Count; i++)
{
result[keys[i]] = values[i];
}
#if NET45PLUS
return new ReadOnlyDictionary<int, T>(result);
#else
return result;
#endif
}
}
}

View File

@ -2,19 +2,14 @@
* Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root.
*/
using Antlr4.Runtime;
using Antlr4.Runtime.Sharpen;
using System.IO;
namespace Antlr4.Runtime
{
/// <summary>How to emit recognition errors.</summary>
/// <remarks>How to emit recognition errors.</remarks>
#if COMPACT
public interface IAntlrErrorListener<TSymbol>
#else
public interface IAntlrErrorListener<in TSymbol>
#endif
{
/// <summary>Upon syntax error, notify any interested parties.</summary>
/// <remarks>

View File

@ -4,10 +4,6 @@
*/
using System;
#if COMPACT
using OperationCanceledException = System.Exception;
#endif
namespace Antlr4.Runtime.Misc
{
/// <summary>This exception is thrown to cancel a parsing operation.</summary>
@ -22,7 +18,7 @@ namespace Antlr4.Runtime.Misc
/// response to a parse error.
/// </remarks>
/// <author>Sam Harwell</author>
[System.Serializable]
[Serializable]
public class ParseCanceledException : OperationCanceledException
{
public ParseCanceledException()

View File

@ -3,17 +3,12 @@
* can be found in the LICENSE.txt file in the project root.
*/
#if NET45PLUS
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Security;
using System.Text;
using Antlr4.Runtime;
using Antlr4.Runtime.Atn;
using Antlr4.Runtime.Misc;
using Antlr4.Runtime.Sharpen;
namespace Antlr4.Runtime.Misc
@ -87,7 +82,7 @@ namespace Antlr4.Runtime.Misc
{
string[] ruleNames = GetRuleNames(recognizerType);
int[] ruleVersions = GetRuleVersions(recognizerType, ruleNames);
RuleDependencyChecker.RuleRelations relations = ExtractRuleRelations(recognizerType);
RuleRelations relations = ExtractRuleRelations(recognizerType);
StringBuilder errors = new StringBuilder();
foreach (Tuple<RuleDependencyAttribute, ICustomAttributeProvider> dependency in dependencies)
{
@ -314,13 +309,9 @@ namespace Antlr4.Runtime.Misc
foreach (MethodInfo method in clazz.DeclaredMethods)
{
GetElementDependencies(AsCustomAttributeProvider(method), result);
#if COMPACT
if (method.ReturnTypeCustomAttributes != null)
GetElementDependencies(AsCustomAttributeProvider(method.ReturnTypeCustomAttributes), result);
#else
if (method.ReturnParameter != null)
GetElementDependencies(AsCustomAttributeProvider(method.ReturnParameter), result);
#endif
foreach (ParameterInfo parameter in method.GetParameters())
GetElementDependencies(AsCustomAttributeProvider(parameter), result);
@ -459,7 +450,6 @@ namespace Antlr4.Runtime.Misc
{
}
#if PORTABLE || DOTNETCORE
public interface ICustomAttributeProvider
{
object[] GetCustomAttributes(Type attributeType, bool inherit);
@ -544,617 +534,5 @@ namespace Antlr4.Runtime.Misc
return _provider.GetCustomAttributes(attributeType, inherit).ToArray();
}
}
#else
protected static ICustomAttributeProvider AsCustomAttributeProvider(ICustomAttributeProvider obj)
{
return obj;
}
#endif
}
}
#else
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Security;
using System.Text;
using Antlr4.Runtime;
using Antlr4.Runtime.Atn;
using Antlr4.Runtime.Misc;
using Antlr4.Runtime.Sharpen;
namespace Antlr4.Runtime.Misc
{
/// <author>Sam Harwell</author>
public class RuleDependencyChecker
{
#if false
private static readonly Logger Logger = Logger.GetLogger(typeof(Antlr4.Runtime.Misc.RuleDependencyChecker).FullName);
#endif
private const BindingFlags AllDeclaredStaticMembers = BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static;
private const BindingFlags AllDeclaredMembers = AllDeclaredStaticMembers | BindingFlags.Instance;
private static readonly HashSet<string> checkedAssemblies = new HashSet<string>();
public static void CheckDependencies(Assembly assembly)
{
if (IsChecked(assembly))
{
return;
}
IList<Type> typesToCheck = GetTypesToCheck(assembly);
ArrayList<Tuple<RuleDependencyAttribute, ICustomAttributeProvider>> dependencies = new ArrayList<Tuple<RuleDependencyAttribute, ICustomAttributeProvider>>();
foreach (Type clazz in typesToCheck)
{
dependencies.AddRange(GetDependencies(clazz));
}
if (dependencies.Count > 0)
{
IDictionary<Type, IList<Tuple<RuleDependencyAttribute, ICustomAttributeProvider>>> recognizerDependencies = new Dictionary<Type, IList<Tuple<RuleDependencyAttribute, ICustomAttributeProvider>>>();
foreach (Tuple<RuleDependencyAttribute, ICustomAttributeProvider> dependency in dependencies)
{
Type recognizerType = dependency.Item1.Recognizer;
IList<Tuple<RuleDependencyAttribute, ICustomAttributeProvider>> list;
if (!recognizerDependencies.TryGetValue(recognizerType, out list))
{
list = new ArrayList<Tuple<RuleDependencyAttribute, ICustomAttributeProvider>>();
recognizerDependencies[recognizerType] = list;
}
list.Add(dependency);
}
foreach (KeyValuePair<Type, IList<Tuple<RuleDependencyAttribute, ICustomAttributeProvider>>> entry in recognizerDependencies)
{
//processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE, String.format("ANTLR 4: Validating {0} dependencies on rules in {1}.", entry.getValue().size(), entry.getKey().toString()));
CheckDependencies(entry.Value, entry.Key);
}
}
MarkChecked(assembly);
}
private static IList<Type> GetTypesToCheck(Assembly assembly)
{
return assembly.GetTypes();
}
private static bool IsChecked(Assembly assembly)
{
lock (checkedAssemblies)
{
return checkedAssemblies.Contains(assembly.FullName);
}
}
private static void MarkChecked(Assembly assembly)
{
lock (checkedAssemblies)
{
checkedAssemblies.Add(assembly.FullName);
}
}
private static void CheckDependencies(IList<Tuple<RuleDependencyAttribute, ICustomAttributeProvider>> dependencies, Type recognizerType)
{
string[] ruleNames = GetRuleNames(recognizerType);
int[] ruleVersions = GetRuleVersions(recognizerType, ruleNames);
RuleDependencyChecker.RuleRelations relations = ExtractRuleRelations(recognizerType);
StringBuilder errors = new StringBuilder();
foreach (Tuple<RuleDependencyAttribute, ICustomAttributeProvider> dependency in dependencies)
{
#if DOTNETCORE
if (!dependency.Item1.Recognizer.GetTypeInfo().IsAssignableFrom(recognizerType))
#else
if (!dependency.Item1.Recognizer.IsAssignableFrom(recognizerType))
#endif
{
continue;
}
// this is the rule in the dependency set with the highest version number
int effectiveRule = dependency.Item1.Rule;
if (effectiveRule < 0 || effectiveRule >= ruleVersions.Length)
{
string message = string.Format("Rule dependency on unknown rule {0}@{1} in {2}", dependency.Item1.Rule, dependency.Item1.Version, dependency.Item1.Recognizer.ToString());
errors.AppendLine(dependency.Item2.ToString());
errors.AppendLine(message);
continue;
}
Dependents dependents = Dependents.Self | dependency.Item1.Dependents;
ReportUnimplementedDependents(errors, dependency, dependents);
BitSet @checked = new BitSet();
int highestRequiredDependency = CheckDependencyVersion(errors, dependency, ruleNames, ruleVersions, effectiveRule, null);
if ((dependents & Dependents.Parents) != 0)
{
BitSet parents = relations.parents[dependency.Item1.Rule];
for (int parent = parents.NextSetBit(0); parent >= 0; parent = parents.NextSetBit(parent + 1))
{
if (parent < 0 || parent >= ruleVersions.Length || @checked.Get(parent))
{
continue;
}
@checked.Set(parent);
int required = CheckDependencyVersion(errors, dependency, ruleNames, ruleVersions, parent, "parent");
highestRequiredDependency = Math.Max(highestRequiredDependency, required);
}
}
if ((dependents & Dependents.Children) != 0)
{
BitSet children = relations.children[dependency.Item1.Rule];
for (int child = children.NextSetBit(0); child >= 0; child = children.NextSetBit(child + 1))
{
if (child < 0 || child >= ruleVersions.Length || @checked.Get(child))
{
continue;
}
@checked.Set(child);
int required = CheckDependencyVersion(errors, dependency, ruleNames, ruleVersions, child, "child");
highestRequiredDependency = Math.Max(highestRequiredDependency, required);
}
}
if ((dependents & Dependents.Ancestors) != 0)
{
BitSet ancestors = relations.GetAncestors(dependency.Item1.Rule);
for (int ancestor = ancestors.NextSetBit(0); ancestor >= 0; ancestor = ancestors.NextSetBit(ancestor + 1))
{
if (ancestor < 0 || ancestor >= ruleVersions.Length || @checked.Get(ancestor))
{
continue;
}
@checked.Set(ancestor);
int required = CheckDependencyVersion(errors, dependency, ruleNames, ruleVersions, ancestor, "ancestor");
highestRequiredDependency = Math.Max(highestRequiredDependency, required);
}
}
if ((dependents & Dependents.Descendants) != 0)
{
BitSet descendants = relations.GetDescendants(dependency.Item1.Rule);
for (int descendant = descendants.NextSetBit(0); descendant >= 0; descendant = descendants.NextSetBit(descendant + 1))
{
if (descendant < 0 || descendant >= ruleVersions.Length || @checked.Get(descendant))
{
continue;
}
@checked.Set(descendant);
int required = CheckDependencyVersion(errors, dependency, ruleNames, ruleVersions, descendant, "descendant");
highestRequiredDependency = Math.Max(highestRequiredDependency, required);
}
}
int declaredVersion = dependency.Item1.Version;
if (declaredVersion > highestRequiredDependency)
{
string message = string.Format("Rule dependency version mismatch: {0} has maximum dependency version {1} (expected {2}) in {3}", ruleNames[dependency.Item1.Rule], highestRequiredDependency, declaredVersion, dependency.Item1.Recognizer.ToString());
errors.AppendLine(dependency.Item2.ToString());
errors.AppendLine(message);
}
}
if (errors.Length > 0)
{
throw new InvalidOperationException(errors.ToString());
}
}
private static readonly Dependents ImplementedDependents = Dependents.Self | Dependents.Parents | Dependents.Children | Dependents.Ancestors | Dependents.Descendants;
private static void ReportUnimplementedDependents(StringBuilder errors, Tuple<RuleDependencyAttribute, ICustomAttributeProvider> dependency, Dependents dependents)
{
Dependents unimplemented = dependents;
unimplemented &= ~ImplementedDependents;
if (unimplemented != Dependents.None)
{
string message = string.Format("Cannot validate the following dependents of rule {0}: {1}", dependency.Item1.Rule, unimplemented);
errors.AppendLine(message);
}
}
private static int CheckDependencyVersion(StringBuilder errors, Tuple<RuleDependencyAttribute, ICustomAttributeProvider> dependency, string[] ruleNames, int[] ruleVersions, int relatedRule, string relation)
{
string ruleName = ruleNames[dependency.Item1.Rule];
string path;
if (relation == null)
{
path = ruleName;
}
else
{
string mismatchedRuleName = ruleNames[relatedRule];
path = string.Format("rule {0} ({1} of {2})", mismatchedRuleName, relation, ruleName);
}
int declaredVersion = dependency.Item1.Version;
int actualVersion = ruleVersions[relatedRule];
if (actualVersion > declaredVersion)
{
string message = string.Format("Rule dependency version mismatch: {0} has version {1} (expected <= {2}) in {3}", path, actualVersion, declaredVersion, dependency.Item1.Recognizer.ToString());
errors.AppendLine(dependency.Item2.ToString());
errors.AppendLine(message);
}
return actualVersion;
}
private static int[] GetRuleVersions(Type recognizerClass, string[] ruleNames)
{
int[] versions = new int[ruleNames.Length];
#if DOTNETCORE
FieldInfo[] fields = recognizerClass.GetTypeInfo().GetFields();
#else
FieldInfo[] fields = recognizerClass.GetFields();
#endif
foreach (FieldInfo field in fields)
{
bool isStatic = field.IsStatic;
bool isInteger = field.FieldType == typeof(int);
if (isStatic && isInteger && field.Name.StartsWith("RULE_"))
{
try
{
string name = field.Name.Substring("RULE_".Length);
if (name.Length == 0 || !System.Char.IsLower(name[0]))
{
continue;
}
int index = (int)field.GetValue(null);
if (index < 0 || index >= versions.Length)
{
#if false
object[] @params = new object[] { index, field.Name, recognizerClass.Name };
Logger.Log(Level.Warning, "Rule index {0} for rule ''{1}'' out of bounds for recognizer {2}.", @params);
#endif
continue;
}
MethodInfo ruleMethod = GetRuleMethod(recognizerClass, name);
if (ruleMethod == null)
{
#if false
object[] @params = new object[] { name, recognizerClass.Name };
Logger.Log(Level.Warning, "Could not find rule method for rule ''{0}'' in recognizer {1}.", @params);
#endif
continue;
}
#if DOTNETCORE
RuleVersionAttribute ruleVersion = ruleMethod.GetCustomAttribute<RuleVersionAttribute>();
#else
RuleVersionAttribute ruleVersion = (RuleVersionAttribute)Attribute.GetCustomAttribute(ruleMethod, typeof(RuleVersionAttribute));
#endif
int version = ruleVersion != null ? ruleVersion.Version : 0;
versions[index] = version;
}
catch (ArgumentException)
{
#if false
Logger.Log(Level.Warning, null, ex);
#else
throw;
#endif
}
catch (MemberAccessException)
{
#if false
Logger.Log(Level.Warning, null, ex);
#else
throw;
#endif
}
}
}
return versions;
}
private static MethodInfo GetRuleMethod(Type recognizerClass, string name)
{
#if DOTNETCORE
MethodInfo[] declaredMethods = recognizerClass.GetTypeInfo().GetMethods();
#else
MethodInfo[] declaredMethods = recognizerClass.GetMethods();
#endif
foreach (MethodInfo method in declaredMethods)
{
#if DOTNETCORE
if (method.Name.Equals(name) && method.IsDefined(typeof(RuleVersionAttribute)))
#else
if (method.Name.Equals(name) && Attribute.IsDefined(method, typeof(RuleVersionAttribute)))
#endif
{
return method;
}
}
return null;
}
private static string[] GetRuleNames(Type recognizerClass)
{
#if DOTNETCORE
FieldInfo ruleNames = recognizerClass.GetTypeInfo().GetField("ruleNames");
#else
FieldInfo ruleNames = recognizerClass.GetField("ruleNames");
#endif
return (string[])ruleNames.GetValue(null);
}
public static IList<Tuple<RuleDependencyAttribute, ICustomAttributeProvider>> GetDependencies(Type clazz)
{
IList<Tuple<RuleDependencyAttribute, ICustomAttributeProvider>> result = new ArrayList<Tuple<RuleDependencyAttribute, ICustomAttributeProvider>>();
#if DOTNETCORE
GetElementDependencies(AsCustomAttributeProvider(clazz.GetTypeInfo()), result);
#else
GetElementDependencies(AsCustomAttributeProvider(clazz), result);
#endif
#if DOTNETCORE
foreach (ConstructorInfo ctor in clazz.GetTypeInfo().GetConstructors(AllDeclaredMembers))
#else
foreach (ConstructorInfo ctor in clazz.GetConstructors(AllDeclaredMembers))
#endif
{
GetElementDependencies(AsCustomAttributeProvider(ctor), result);
foreach (ParameterInfo parameter in ctor.GetParameters())
GetElementDependencies(AsCustomAttributeProvider(parameter), result);
}
#if DOTNETCORE
foreach (FieldInfo field in clazz.GetTypeInfo().GetFields(AllDeclaredMembers))
#else
foreach (FieldInfo field in clazz.GetFields(AllDeclaredMembers))
#endif
{
GetElementDependencies(AsCustomAttributeProvider(field), result);
}
#if DOTNETCORE
foreach (MethodInfo method in clazz.GetTypeInfo().GetMethods(AllDeclaredMembers))
#else
foreach (MethodInfo method in clazz.GetMethods(AllDeclaredMembers))
#endif
{
GetElementDependencies(AsCustomAttributeProvider(method), result);
#if COMPACT
if (method.ReturnTypeCustomAttributes != null)
GetElementDependencies(AsCustomAttributeProvider(method.ReturnTypeCustomAttributes), result);
#else
if (method.ReturnParameter != null)
GetElementDependencies(AsCustomAttributeProvider(method.ReturnParameter), result);
#endif
foreach (ParameterInfo parameter in method.GetParameters())
GetElementDependencies(AsCustomAttributeProvider(parameter), result);
}
return result;
}
private static void GetElementDependencies(ICustomAttributeProvider annotatedElement, IList<Tuple<RuleDependencyAttribute, ICustomAttributeProvider>> result)
{
foreach (RuleDependencyAttribute dependency in annotatedElement.GetCustomAttributes(typeof(RuleDependencyAttribute), true))
{
result.Add(Tuple.Create(dependency, annotatedElement));
}
}
private static RuleDependencyChecker.RuleRelations ExtractRuleRelations(Type recognizer)
{
string serializedATN = GetSerializedATN(recognizer);
if (serializedATN == null)
{
return null;
}
ATN atn = new ATNDeserializer().Deserialize(serializedATN.ToCharArray());
RuleDependencyChecker.RuleRelations relations = new RuleDependencyChecker.RuleRelations(atn.ruleToStartState.Length);
foreach (ATNState state in atn.states)
{
if (!state.epsilonOnlyTransitions)
{
continue;
}
foreach (Transition transition in state.transitions)
{
if (transition.TransitionType != TransitionType.RULE)
{
continue;
}
RuleTransition ruleTransition = (RuleTransition)transition;
relations.AddRuleInvocation(state.ruleIndex, ruleTransition.target.ruleIndex);
}
}
return relations;
}
private static string GetSerializedATN(Type recognizerClass)
{
#if DOTNETCORE
FieldInfo serializedAtnField = recognizerClass.GetTypeInfo().GetField("_serializedATN", AllDeclaredStaticMembers);
#else
FieldInfo serializedAtnField = recognizerClass.GetField("_serializedATN", AllDeclaredStaticMembers);
#endif
if (serializedAtnField != null)
return (string)serializedAtnField.GetValue(null);
#if DOTNETCORE
if (recognizerClass.GetTypeInfo().BaseType != null)
return GetSerializedATN(recognizerClass.GetTypeInfo().BaseType);
#else
if (recognizerClass.BaseType != null)
return GetSerializedATN(recognizerClass.BaseType);
#endif
return null;
}
private sealed class RuleRelations
{
public readonly BitSet[] parents;
public readonly BitSet[] children;
public RuleRelations(int ruleCount)
{
parents = new BitSet[ruleCount];
for (int i = 0; i < ruleCount; i++)
{
parents[i] = new BitSet();
}
children = new BitSet[ruleCount];
for (int i_1 = 0; i_1 < ruleCount; i_1++)
{
children[i_1] = new BitSet();
}
}
public bool AddRuleInvocation(int caller, int callee)
{
if (caller < 0)
{
// tokens rule
return false;
}
if (children[caller].Get(callee))
{
// already added
return false;
}
children[caller].Set(callee);
parents[callee].Set(caller);
return true;
}
public BitSet GetAncestors(int rule)
{
BitSet ancestors = new BitSet();
ancestors.Or(parents[rule]);
while (true)
{
int cardinality = ancestors.Cardinality();
for (int i = ancestors.NextSetBit(0); i >= 0; i = ancestors.NextSetBit(i + 1))
{
ancestors.Or(parents[i]);
}
if (ancestors.Cardinality() == cardinality)
{
// nothing changed
break;
}
}
return ancestors;
}
public BitSet GetDescendants(int rule)
{
BitSet descendants = new BitSet();
descendants.Or(children[rule]);
while (true)
{
int cardinality = descendants.Cardinality();
for (int i = descendants.NextSetBit(0); i >= 0; i = descendants.NextSetBit(i + 1))
{
descendants.Or(children[i]);
}
if (descendants.Cardinality() == cardinality)
{
// nothing changed
break;
}
}
return descendants;
}
}
private RuleDependencyChecker()
{
}
#if PORTABLE
public interface ICustomAttributeProvider
{
object[] GetCustomAttributes(Type attributeType, bool inherit);
}
protected static ICustomAttributeProvider AsCustomAttributeProvider(Type type)
{
return new TypeCustomAttributeProvider(type);
}
protected static ICustomAttributeProvider AsCustomAttributeProvider(MethodBase method)
{
return new MethodBaseCustomAttributeProvider(method);
}
protected static ICustomAttributeProvider AsCustomAttributeProvider(ParameterInfo parameter)
{
return new ParameterInfoCustomAttributeProvider(parameter);
}
protected static ICustomAttributeProvider AsCustomAttributeProvider(FieldInfo field)
{
return new FieldInfoCustomAttributeProvider(field);
}
protected sealed class TypeCustomAttributeProvider : ICustomAttributeProvider
{
private readonly Type _provider;
public TypeCustomAttributeProvider(Type provider)
{
_provider = provider;
}
public object[] GetCustomAttributes(Type attributeType, bool inherit)
{
return Attribute.GetCustomAttributes(_provider, attributeType, inherit);
}
}
protected sealed class MethodBaseCustomAttributeProvider : ICustomAttributeProvider
{
private readonly MethodBase _provider;
public MethodBaseCustomAttributeProvider(MethodBase provider)
{
_provider = provider;
}
public object[] GetCustomAttributes(Type attributeType, bool inherit)
{
return Attribute.GetCustomAttributes(_provider, attributeType, inherit);
}
}
protected sealed class ParameterInfoCustomAttributeProvider : ICustomAttributeProvider
{
private readonly ParameterInfo _provider;
public ParameterInfoCustomAttributeProvider(ParameterInfo provider)
{
_provider = provider;
}
public object[] GetCustomAttributes(Type attributeType, bool inherit)
{
return Attribute.GetCustomAttributes(_provider, attributeType, inherit);
}
}
protected sealed class FieldInfoCustomAttributeProvider : ICustomAttributeProvider
{
private readonly FieldInfo _provider;
public FieldInfoCustomAttributeProvider(FieldInfo provider)
{
_provider = provider;
}
public object[] GetCustomAttributes(Type attributeType, bool inherit)
{
return Attribute.GetCustomAttributes(_provider, attributeType, inherit);
}
}
#else
protected static ICustomAttributeProvider AsCustomAttributeProvider(ICustomAttributeProvider obj)
{
return obj;
}
#endif
}
}
#endif

View File

@ -5,7 +5,6 @@
using System;
using System.Collections.Generic;
using System.Text;
using Antlr4.Runtime.Sharpen;
namespace Antlr4.Runtime.Misc
{
@ -13,20 +12,7 @@ namespace Antlr4.Runtime.Misc
{
public static string Join<T>(string separator, IEnumerable<T> items)
{
#if NET40PLUS
return string.Join(separator, items);
#else
ArrayList<string> elements = new ArrayList<string>();
foreach (T item in items)
{
if (item == null)
elements.Add("");
else
elements.Add(item.ToString());
}
return string.Join(separator, elements.ToArray());
#endif
}
public static int NumNonnull(object[] data)

View File

@ -19,7 +19,6 @@ namespace Antlr4.Runtime
/// <remarks>This is all the parsing support code essentially; most of it is error recovery stuff.</remarks>
public abstract class Parser : Recognizer<IToken, ParserATNSimulator>
{
#if !PORTABLE
public class TraceListener : IParseTreeListener
{
@ -58,7 +57,6 @@ namespace Antlr4.Runtime
private readonly Parser _enclosing;
private readonly TextWriter _output;
}
#endif
public class TrimToSizeListener : IParseTreeListener
{
@ -133,7 +131,6 @@ namespace Antlr4.Runtime
/// <seealso cref="BuildParseTree"/>
private bool _buildParseTrees = true;
#if !PORTABLE
/// <summary>
/// When
/// <see cref="Trace"/>
@ -149,7 +146,6 @@ namespace Antlr4.Runtime
/// other parser methods.
/// </summary>
private Parser.TraceListener _tracer;
#endif
/// <summary>
/// The list of
@ -192,9 +188,7 @@ namespace Antlr4.Runtime
_errHandler.Reset(this);
_ctx = null;
_syntaxErrors = 0;
#if !PORTABLE
Trace = false;
#endif
_precedenceStack.Clear();
_precedenceStack.Add(0);
ATNSimulator interpreter = Interpreter;
@ -1146,7 +1140,6 @@ namespace Antlr4.Runtime
return s;
}
#if !PORTABLE
/// <summary>For debugging and other purposes.</summary>
/// <remarks>For debugging and other purposes.</remarks>
public virtual void DumpDFA()
@ -1167,7 +1160,6 @@ namespace Antlr4.Runtime
}
}
}
#endif
public virtual string SourceName
{
@ -1214,7 +1206,6 @@ namespace Antlr4.Runtime
}
}
#if !PORTABLE
/// <summary>
/// During a parse is sometimes useful to listen in on the rule entry and exit
/// events as well as token matches.
@ -1258,6 +1249,5 @@ namespace Antlr4.Runtime
}
}
}
#endif
}
}

View File

@ -279,11 +279,7 @@ namespace Antlr4.Runtime
return null;
}
#if (NET45PLUS && !DOTNETCORE)
public virtual IReadOnlyList<ITerminalNode> GetTokens(int ttype)
#else
public virtual ITerminalNode[] GetTokens(int ttype)
#endif
{
if (children == null)
{
@ -310,11 +306,8 @@ namespace Antlr4.Runtime
{
return Collections.EmptyList<ITerminalNode>();
}
#if (NET45PLUS && !DOTNETCORE)
return tokens;
#else
return tokens.ToArray();
#endif
}
public virtual T GetRuleContext<T>(int i)
@ -323,13 +316,8 @@ namespace Antlr4.Runtime
return GetChild<T>(i);
}
#if (NET45PLUS && !DOTNETCORE)
public virtual IReadOnlyList<T> GetRuleContexts<T>()
where T : Antlr4.Runtime.ParserRuleContext
#else
public virtual T[] GetRuleContexts<T>()
where T : Antlr4.Runtime.ParserRuleContext
#endif
{
if (children == null)
{
@ -351,11 +339,8 @@ namespace Antlr4.Runtime
{
return Collections.EmptyList<T>();
}
#if (NET45PLUS && !DOTNETCORE)
return contexts;
#else
return contexts.ToArray();
#endif
}
public override int ChildCount

View File

@ -4,7 +4,6 @@
*/
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
@ -20,17 +19,13 @@ using System.Runtime.InteropServices;
[assembly: AssemblyCulture("")]
[assembly: CLSCompliant(true)]
#if !PORTABLE || NET45PLUS
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
#if !PORTABLE
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("bc228eb9-e79c-4e5a-a1b9-0434ea566bab")]
#endif
#endif
// Version information for an assembly consists of the following four values:
//
@ -43,7 +38,6 @@ using System.Runtime.InteropServices;
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("4.9")]
#if !COMPACT
[assembly: AssemblyFileVersion("4.9")]
[assembly: AssemblyInformationalVersion("4.9")]
#endif

View File

@ -4,13 +4,10 @@
*/
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using Antlr4.Runtime.Atn;
using Antlr4.Runtime.Misc;
#if NET40PLUS
using System.Runtime.CompilerServices;
#endif
namespace Antlr4.Runtime
{
public abstract class Recognizer<Symbol, ATNInterpreter> : IRecognizer
@ -18,17 +15,13 @@ namespace Antlr4.Runtime
{
public const int Eof = -1;
#if NET40PLUS
private static readonly ConditionalWeakTable<IVocabulary, IDictionary<string, int>> tokenTypeMapCache = new ConditionalWeakTable<IVocabulary, IDictionary<string, int>>();
private static readonly ConditionalWeakTable<string[], IDictionary<string, int>> ruleIndexMapCache = new ConditionalWeakTable<string[], IDictionary<string, int>>();
#endif
[NotNull]
private IAntlrErrorListener<Symbol>[] _listeners =
{
#if !PORTABLE
ConsoleErrorListener<Symbol>.Instance
#endif
};
private ATNInterpreter _interp;
@ -74,11 +67,7 @@ namespace Antlr4.Runtime
{
get
{
#if NET40PLUS
return tokenTypeMapCache.GetValue(Vocabulary, CreateTokenTypeMap);
#else
return CreateTokenTypeMap(Vocabulary);
#endif
}
}
@ -117,11 +106,8 @@ namespace Antlr4.Runtime
{
throw new NotSupportedException("The current recognizer does not provide a list of rule names.");
}
#if NET40PLUS
return ruleIndexMapCache.GetValue(ruleNames, Utils.ToMap);
#else
return Utils.ToMap(ruleNames);
#endif
}
}

View File

@ -4,7 +4,6 @@
*/
namespace Antlr4.Runtime.Sharpen
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
@ -15,11 +14,7 @@ namespace Antlr4.Runtime.Sharpen
return EmptyListImpl<T>.Instance;
}
#if NET45PLUS
public static ReadOnlyDictionary<TKey, TValue> EmptyMap<TKey, TValue>()
#else
public static IDictionary<TKey, TValue> EmptyMap<TKey, TValue>()
#endif
{
return EmptyMapImpl<TKey, TValue>.Instance;
}
@ -29,17 +24,9 @@ namespace Antlr4.Runtime.Sharpen
return new ReadOnlyCollection<T>(new T[] { item });
}
#if NET45PLUS
public static ReadOnlyDictionary<TKey, TValue> SingletonMap<TKey, TValue>(TKey key, TValue value)
#else
public static IDictionary<TKey, TValue> SingletonMap<TKey, TValue>(TKey key, TValue value)
#endif
{
#if NET45PLUS
return new ReadOnlyDictionary<TKey,TValue>(new Dictionary<TKey, TValue> { { key, value } });
#else
return new Dictionary<TKey, TValue> { { key, value } };
#endif
}
private static class EmptyListImpl<T>
@ -49,18 +36,8 @@ namespace Antlr4.Runtime.Sharpen
private static class EmptyMapImpl<TKey, TValue>
{
#if NET45PLUS
public static readonly ReadOnlyDictionary<TKey, TValue> Instance =
new ReadOnlyDictionary<TKey, TValue>(new Dictionary<TKey, TValue>());
#else
public static IDictionary<TKey, TValue> Instance
{
get
{
return new Dictionary<TKey, TValue>();
}
}
#endif
}
}

View File

@ -3,7 +3,7 @@
* can be found in the LICENSE.txt file in the project root.
*/
#if PORTABLE || DOTNETCORE
#if NETSTANDARD20
namespace System
{
@ -13,5 +13,4 @@ namespace System
}
}
#endif
#endif

View File

@ -5,7 +5,6 @@
namespace Antlr4.Runtime.Sharpen
{
using System.Collections.Generic;
using Antlr4.Runtime.Misc;
internal static class ListExtensions
{
@ -16,8 +15,5 @@ namespace Antlr4.Runtime.Sharpen
list[index] = value;
return previous;
}
}
}
}

View File

@ -621,9 +621,7 @@ namespace Antlr4.Runtime
// kill first delete
rop.index = Math.Min(prevRop.index, rop.index);
rop.lastIndex = Math.Max(prevRop.lastIndex, rop.lastIndex);
#if !PORTABLE
System.Console.Out.WriteLine("new rop " + rop);
#endif
}
else
{

View File

@ -16,11 +16,7 @@ namespace Antlr4.Runtime.Tree
/// .
/// </remarks>
/// <author>Sam Harwell</author>
#if COMPACT
public interface IParseTreeVisitor<Result>
#else
public interface IParseTreeVisitor<out Result>
#endif
{
/// <summary>Visit a parse tree, and return a user-defined result of the operation.</summary>
/// <remarks>Visit a parse tree, and return a user-defined result of the operation.</remarks>

View File

@ -2,11 +2,7 @@
* Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root.
*/
#if NET40PLUS
using System.Collections.Concurrent;
#else
using Antlr4.Runtime.Sharpen;
#endif
namespace Antlr4.Runtime.Tree
{