本文整理汇总了C#中System.Management.Automation.Language.Token类的典型用法代码示例。如果您正苦于以下问题:C# Token类的具体用法?C# Token怎么用?C# Token使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
Token类属于System.Management.Automation.Language命名空间,在下文中一共展示了Token类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。
示例1: ErrorStatementAst
internal ErrorStatementAst(IScriptExtent extent, Token kind, IEnumerable<KeyValuePair<string, Tuple<Token, Ast>>> flags, IEnumerable<Ast> conditions, IEnumerable<Ast> bodies) : base(extent)
{
if (kind == null)
{
throw PSTraceSource.NewArgumentNullException("kind");
}
this.Kind = kind;
if ((flags != null) && flags.Any<KeyValuePair<string, Tuple<Token, Ast>>>())
{
this.Flags = new Dictionary<string, Tuple<Token, Ast>>(StringComparer.OrdinalIgnoreCase);
foreach (KeyValuePair<string, Tuple<Token, Ast>> pair in flags)
{
if (!this.Flags.ContainsKey(pair.Key))
{
this.Flags.Add(pair.Key, pair.Value);
if (pair.Value.Item2 != null)
{
base.SetParent(pair.Value.Item2);
}
}
}
}
if ((conditions != null) && conditions.Any<Ast>())
{
this.Conditions = new ReadOnlyCollection<Ast>(conditions.ToArray<Ast>());
base.SetParents(conditions);
}
if ((bodies != null) && bodies.Any<Ast>())
{
this.Bodies = new ReadOnlyCollection<Ast>(bodies.ToArray<Ast>());
base.SetParents(bodies);
}
}
开发者ID:nickchal,项目名称:pash,代码行数:33,代码来源:ErrorStatementAst.cs
示例2: ToClassificationInfo
private static void ToClassificationInfo(Token token, int start, int length, ICollection<ClassificationInfo> classificationInfo)
{
if (token != null && length > 0)
{
classificationInfo.Add(new ClassificationInfo(start, length, GetClassificationType(token)));
}
}
开发者ID:vairam-svs,项目名称:poshtools,代码行数:7,代码来源:ClassifierServices.cs
示例3: CompletionAnalysis
internal CompletionAnalysis(Ast ast, Token[] tokens, IScriptPosition cursorPosition, Hashtable options)
{
_ast = ast;
_tokens = tokens;
_cursorPosition = cursorPosition;
_options = options;
}
开发者ID:dfinke,项目名称:powershell,代码行数:7,代码来源:CompletionAnalysis.cs
示例4: GetSingleAstRequiredModules
private static List<string> GetSingleAstRequiredModules(Ast ast, Token[] tokens)
{
List<string> modules = new List<string>();
List<string> resources = new List<string>();
var imports = tokens.Where(token =>
String.Compare(token.Text, "Import-DscResource", StringComparison.OrdinalIgnoreCase) == 0);
//
// Create a function with the same name as Import-DscResource keyword and use powershell
// argument function binding to emulate Import-DscResource argument binding.
//
InitialSessionState initialSessionState = InitialSessionState.Create();
SessionStateFunctionEntry importDscResourcefunctionEntry = new SessionStateFunctionEntry(
"Import-DscResource", @"param($Name, $ModuleName)
if ($ModuleName)
{
foreach ($m in $ModuleName) { $global:modules.Add($m) }
} else {
foreach ($n in $Name) { $global:resources.Add($n) }
}
");
initialSessionState.Commands.Add(importDscResourcefunctionEntry);
initialSessionState.LanguageMode = PSLanguageMode.RestrictedLanguage;
var moduleVarEntry = new SessionStateVariableEntry("modules", modules, "");
var resourcesVarEntry = new SessionStateVariableEntry("resources", resources, "");
initialSessionState.Variables.Add(moduleVarEntry);
initialSessionState.Variables.Add(resourcesVarEntry);
using (System.Management.Automation.PowerShell powerShell = System.Management.Automation.PowerShell.Create(initialSessionState))
{
foreach (var import in imports)
{
int startOffset = import.Extent.StartOffset;
var asts = ast.FindAll(a => IsCandidateForImportDscResourceAst(a, startOffset), true);
int longestLen = -1;
Ast longestCandidate = null;
foreach (var candidatAst in asts)
{
int curLen = candidatAst.Extent.EndOffset - candidatAst.Extent.StartOffset;
if (curLen > longestLen)
{
longestCandidate = candidatAst;
longestLen = curLen;
}
}
// longestCandidate should contain AST for import-dscresource, like "Import-DSCResource -Module x -Name y".
if (longestCandidate != null)
{
string importText = longestCandidate.Extent.Text;
// We invoke-command "importText" here. Script injection is prevented:
// We checked that file represents a valid AST without errors.
powerShell.AddScript(importText);
powerShell.Invoke();
powerShell.Commands.Clear();
}
}
}
modules.AddRange(resources.Select(GetModuleNameForDscResource));
return modules;
}
开发者ID:randorfer,项目名称:azure-powershell,代码行数:60,代码来源:ConfigurationParsingHelper.cs
示例5: OnLostFocus
/// <summary>
/// Gets called when the window looses focus. If the inspector window is open, we want to close it at this point.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void OnLostFocus(object sender, RoutedEventArgs e)
{
if (_objectInspector == null)
return;
_objectInspector?.Close();
_currentToken = null;
}
开发者ID:peterschen,项目名称:SMAStudio,代码行数:13,代码来源:InsightService.cs
示例6: GetCompletionData
/// <summary>
/// Retrieve completion suggestions
/// </summary>
/// <param name="completionWord">Word to complete</param>
/// <param name="content">Script that we're working with</param>
/// <param name="lineContent">Content of the current line</param>
/// <param name="line">Line object from AvaloneEdit</param>
/// <param name="runbookToken">Token containing the name of the runbook (if not runbook, null)</param>
/// <param name="position">Caret offset</param>
/// <param name="triggerChar">Not used</param>
/// <param name="triggerTag">Counter</param>
public void GetCompletionData(string completionWord, string content, string lineContent, DocumentLine line, Token runbookToken, int position, char? triggerChar, long triggerTag)
{
if (_requestTrigger != 0 && triggerTag <= _requestTrigger)
return;
DismissGetCompletionResults();
ProcessCompletion(content, triggerChar, completionWord, runbookToken, position, triggerTag);
}
开发者ID:peterschen,项目名称:SMAStudio,代码行数:19,代码来源:CompletionProvider.cs
示例7: ExpandableStringExpressionAst
internal ExpandableStringExpressionAst(Token token, string value, string formatString, IEnumerable<ExpressionAst> nestedExpressions) : base(token.Extent)
{
this.FormatExpression = formatString;
this.Value = value;
this.StringConstantType = StringConstantExpressionAst.MapTokenKindToStringContantKind(token);
this.NestedExpressions = new ReadOnlyCollection<ExpressionAst>(nestedExpressions.ToArray<ExpressionAst>());
base.SetParents((IEnumerable<Ast>) this.NestedExpressions);
}
开发者ID:nickchal,项目名称:pash,代码行数:8,代码来源:ExpandableStringExpressionAst.cs
示例8: GetBufferState
/// <summary>
/// Get the state of the buffer - the ast, tokens, errors, and position of the cursor
/// </summary>
public static void GetBufferState(out Ast ast, out Token[] tokens, out ParseError[] parseErrors, out int cursor)
{
_singleton.ParseInput();
ast = _singleton._ast;
tokens = _singleton._tokens;
parseErrors = _singleton._parseErrors;
cursor = _singleton._current;
}
开发者ID:pankajbharti,项目名称:PSReadLine,代码行数:11,代码来源:PublicAPI.cs
示例9: AddSpanForToken
private void AddSpanForToken(Token token, int spanStart, List<ClassificationInfo> classificationInfo)
{
var stringExpandableToken = token as StringExpandableToken;
if (stringExpandableToken != null && stringExpandableToken.NestedTokens != null)
{
AddSpansForStringToken(stringExpandableToken, spanStart, classificationInfo);
}
ToClassificationInfo(token, token.Extent.StartOffset + spanStart, token.Extent.EndOffset - token.Extent.StartOffset, classificationInfo);
}
开发者ID:vairam-svs,项目名称:poshtools,代码行数:10,代码来源:ClassifierServices.cs
示例10: ParseFile
/// <summary>
/// Parse input from the specified file.
/// </summary>
/// <param name="fileName">The name of the file to parse.</param>
/// <param name="tokens">Returns the tokens from parsing the script.</param>
/// <param name="errors">Returns errors, if any, discovered while parsing the script.</param>
/// <returns>The <see cref="ScriptBlockAst"/> that represents the input script file.</returns>
public static ScriptBlockAst ParseFile(string fileName, out Token[] tokens, out ParseError[] errors)
{
const string scriptSchemaExtension = ".schema.psm1";
var parseDscResource = false;
// If the file has the 'schema.psm1' extension, then it is a 'DSC module file' however we don't actually load the
// module at parse time so we can't use the normal mechanisms to bind the module name for configuration commands.
// As an alternative, we extract the base name of the module file and use that as the module name for any keywords exported by this file.
var parser = new Parser();
if (!string.IsNullOrEmpty(fileName) && fileName.Length > scriptSchemaExtension.Length && fileName.EndsWith(scriptSchemaExtension, StringComparison.OrdinalIgnoreCase))
{
parser._keywordModuleName = Path.GetFileName(fileName.Substring(0, fileName.Length - scriptSchemaExtension.Length));
parseDscResource = true;
}
string scriptContents;
try
{
var esi = new ExternalScriptInfo(fileName, fileName);
scriptContents = esi.ScriptContents;
}
catch (Exception e)
{
var emptyExtent = new EmptyScriptExtent();
var errorMsg = string.Format(CultureInfo.CurrentCulture, ParserStrings.FileReadError, e.Message);
errors = new[] { new ParseError(emptyExtent, "FileReadError", errorMsg) };
tokens = Utils.EmptyArray<Token>();
return new ScriptBlockAst(emptyExtent, null, new StatementBlockAst(emptyExtent, null, null), false);
}
var tokenList = new List<Token>();
ScriptBlockAst result;
try
{
if (!parseDscResource)
{
DynamicKeyword.Push();
}
result = parser.Parse(fileName, scriptContents, tokenList, out errors, ParseMode.Default);
}
catch (Exception e)
{
throw new ParseException(ParserStrings.UnrecoverableParserError, e);
}
finally
{
if (!parseDscResource)
{
DynamicKeyword.Pop();
}
}
tokens = tokenList.ToArray();
return result;
}
开发者ID:dfinke,项目名称:powershell,代码行数:61,代码来源:Parser.cs
示例11: PSToken
internal PSToken(Token token)
{
Type = GetPSTokenType(token);
_extent = token.Extent;
if (token is StringToken)
{
_content = ((StringToken)token).Value;
}
else if (token is VariableToken)
{
_content = ((VariableToken)token).VariablePath.ToString();
}
}
开发者ID:40a,项目名称:PowerShell,代码行数:13,代码来源:PSToken.cs
示例12: BlockStatementAst
public BlockStatementAst(IScriptExtent extent, Token kind, StatementBlockAst body) : base(extent)
{
if ((kind == null) || (body == null))
{
throw PSTraceSource.NewArgumentNullException((kind == null) ? "kind" : "body");
}
if ((kind.Kind != TokenKind.Sequence) && (kind.Kind != TokenKind.Parallel))
{
throw PSTraceSource.NewArgumentException("kind");
}
this.Kind = kind;
this.Body = body;
base.SetParent(body);
}
开发者ID:nickchal,项目名称:pash,代码行数:14,代码来源:BlockStatementAst.cs
示例13: GetCommandCompletionParameters
/// <summary>
/// Get the abstract syntax tree, tokens and the cursor position.
/// </summary>
/// <param name="script">The active script.</param>
/// <param name="caretPosition">The caret position.</param>
/// <param name="ast">The AST to get.</param>
/// <param name="tokens">The tokens to get.</param>
/// <param name="cursorPosition">The cursor position to get.</param>
public static void GetCommandCompletionParameters(string script, int caretPosition, out Ast ast, out Token[] tokens, out IScriptPosition cursorPosition)
{
ParseError[] array;
ast = Tokenize(script, out tokens, out array);
if (ast != null)
{
//HACK: Clone with a new offset using private method...
var type = ast.Extent.StartScriptPosition.GetType();
var method = type.GetMethod("CloneWithNewOffset",
BindingFlags.Instance | BindingFlags.NonPublic,
null,
new[] { typeof(int) }, null);
cursorPosition = (IScriptPosition)method.Invoke(ast.Extent.StartScriptPosition, new object[] { caretPosition });
return;
}
cursorPosition = null;
}
开发者ID:peterschen,项目名称:SMAStudio,代码行数:26,代码来源:CommandCompletionHelper.cs
示例14: GetPSTokenType
/// <summary>
/// Map a V3 token to a V2 PSTokenType
/// </summary>
/// <param name="token">The V3 token</param>
/// <returns>The V2 PSTokenType</returns>
public static PSTokenType GetPSTokenType(Token token)
{
if ((token.TokenFlags & TokenFlags.CommandName) != 0)
{
return PSTokenType.Command;
}
if ((token.TokenFlags & TokenFlags.MemberName) != 0)
{
return PSTokenType.Member;
}
if ((token.TokenFlags & TokenFlags.AttributeName) != 0)
{
return PSTokenType.Attribute;
}
if ((token.TokenFlags & TokenFlags.TypeName) != 0)
{
return PSTokenType.Type;
}
return s_tokenKindMapping[(int)token.Kind];
}
开发者ID:40a,项目名称:PowerShell,代码行数:25,代码来源:PSToken.cs
示例15: MapTokenKindToStringContantKind
internal static System.Management.Automation.Language.StringConstantType MapTokenKindToStringContantKind(Token token)
{
switch (token.Kind)
{
case TokenKind.Generic:
return System.Management.Automation.Language.StringConstantType.BareWord;
case TokenKind.StringLiteral:
return System.Management.Automation.Language.StringConstantType.SingleQuoted;
case TokenKind.StringExpandable:
return System.Management.Automation.Language.StringConstantType.DoubleQuoted;
case TokenKind.HereStringLiteral:
return System.Management.Automation.Language.StringConstantType.SingleQuotedHereString;
case TokenKind.HereStringExpandable:
return System.Management.Automation.Language.StringConstantType.DoubleQuotedHereString;
}
throw PSTraceSource.NewInvalidOperationException();
}
开发者ID:nickchal,项目名称:pash,代码行数:21,代码来源:StringConstantExpressionAst.cs
示例16: GetCompletions
/// <summary>
/// Gets completions for the symbol found in the Ast at
/// the given file offset.
/// </summary>
/// <param name="scriptAst">
/// The Ast which will be traversed to find a completable symbol.
/// </param>
/// <param name="currentTokens">
/// The array of tokens corresponding to the scriptAst parameter.
/// </param>
/// <param name="fileOffset">
/// The 1-based file offset at which a symbol will be located.
/// </param>
/// <param name="runspace">
/// The Runspace to use for gathering completions.
/// </param>
/// <returns>
/// A CommandCompletion instance that contains completions for the
/// symbol at the given offset.
/// </returns>
static public CommandCompletion GetCompletions(
Ast scriptAst,
Token[] currentTokens,
int fileOffset,
Runspace runspace)
{
var type = scriptAst.Extent.StartScriptPosition.GetType();
var method =
type.GetMethod(
"CloneWithNewOffset",
BindingFlags.Instance | BindingFlags.NonPublic,
null,
new[] { typeof(int) }, null);
IScriptPosition cursorPosition =
(IScriptPosition)method.Invoke(
scriptAst.Extent.StartScriptPosition,
new object[] { fileOffset });
CommandCompletion commandCompletion = null;
if (runspace.RunspaceAvailability == RunspaceAvailability.Available)
{
using (System.Management.Automation.PowerShell powerShell =
System.Management.Automation.PowerShell.Create())
{
powerShell.Runspace = runspace;
commandCompletion =
CommandCompletion.CompleteInput(
scriptAst,
currentTokens,
cursorPosition,
null,
powerShell);
}
}
return commandCompletion;
}
开发者ID:modulexcite,项目名称:PowerShellEditorServices,代码行数:59,代码来源:AstOperations.cs
示例17: CompleteAgainstStatementFlags
private static bool CompleteAgainstStatementFlags(Ast scriptAst, Ast lastAst, Token token, out TokenKind kind)
{
Func<Ast, bool> predicate = null;
kind = TokenKind.Unknown;
ErrorStatementAst ast = lastAst as ErrorStatementAst;
if (((ast != null) && (ast.Kind != null)) && (ast.Kind.Kind == TokenKind.Switch))
{
kind = TokenKind.Switch;
return true;
}
ScriptBlockAst ast2 = scriptAst as ScriptBlockAst;
if (((token != null) && (token.Kind == TokenKind.Minus)) && (ast2 != null))
{
Tuple<Token, Ast> tuple;
if (predicate == null)
{
predicate = a => IsCursorBeforeExtent(token.Extent.StartScriptPosition, a.Extent);
}
Ast parent = AstSearcher.FindAll(ast2, predicate, true).LastOrDefault<Ast>();
ast = null;
while (parent != null)
{
ast = parent as ErrorStatementAst;
if (ast != null)
{
break;
}
parent = parent.Parent;
}
if ((((ast != null) && (ast.Kind != null)) && ((ast.Kind.Kind == TokenKind.Switch) && (ast.Flags != null))) && (ast.Flags.TryGetValue("--%", out tuple) && IsTokenTheSame(tuple.Item1, token)))
{
kind = TokenKind.Switch;
return true;
}
}
return false;
}
开发者ID:nickchal,项目名称:pash,代码行数:37,代码来源:CompletionAnalysis.cs
示例18: CompleteAgainstSwitchFile
private static bool CompleteAgainstSwitchFile(Ast lastAst, Token tokenBeforeCursor)
{
Tuple<Token, Ast> tuple;
ErrorStatementAst ast = lastAst as ErrorStatementAst;
if ((((ast != null) && (ast.Flags != null)) && ((ast.Kind != null) && (tokenBeforeCursor != null))) && (ast.Kind.Kind.Equals(TokenKind.Switch) && ast.Flags.TryGetValue("file", out tuple)))
{
return (tuple.Item1.Extent.EndOffset == tokenBeforeCursor.Extent.EndOffset);
}
if (!(lastAst.Parent is CommandExpressionAst))
{
return false;
}
PipelineAst parent = lastAst.Parent.Parent as PipelineAst;
if (parent == null)
{
return false;
}
ast = parent.Parent as ErrorStatementAst;
if (((ast == null) || (ast.Kind == null)) || (ast.Flags == null))
{
return false;
}
return ((ast.Kind.Kind.Equals(TokenKind.Switch) && ast.Flags.TryGetValue("file", out tuple)) && (tuple.Item2 == parent));
}
开发者ID:nickchal,项目名称:pash,代码行数:24,代码来源:CompletionAnalysis.cs
示例19: ReallyRender
private void ReallyRender()
{
var text = ParseInput();
int statusLineCount = GetStatusLineCount();
int j = _initialX + (_bufferWidth * Options.ExtraPromptLineCount);
var backgroundColor = _initialBackgroundColor;
var foregroundColor = _initialForegroundColor;
bool afterLastToken = false;
int totalBytes = j;
int bufferWidth = _console.BufferWidth;
var tokenStack = new Stack<SavedTokenState>();
tokenStack.Push(new SavedTokenState
{
Tokens = _tokens,
Index = 0,
BackgroundColor = _initialBackgroundColor,
ForegroundColor = _initialForegroundColor
});
int bufferLineCount;
try
{
_console.StartRender();
bufferLineCount = ConvertOffsetToCoordinates(text.Length).Y - _initialY + 1 + statusLineCount;
if (_consoleBuffer.Length != bufferLineCount * bufferWidth)
{
var newBuffer = new CHAR_INFO[bufferLineCount * bufferWidth];
Array.Copy(_consoleBuffer, newBuffer, _initialX + (Options.ExtraPromptLineCount * _bufferWidth));
if (_consoleBuffer.Length > bufferLineCount * bufferWidth)
{
int consoleBufferOffset = ConvertOffsetToConsoleBufferOffset(text.Length, _initialX + (Options.ExtraPromptLineCount * _bufferWidth));
// Need to erase the extra lines that we won't draw again
for (int i = consoleBufferOffset; i < _consoleBuffer.Length; i++)
{
_consoleBuffer[i] = _space;
}
_console.WriteBufferLines(_consoleBuffer, ref _initialY);
}
_consoleBuffer = newBuffer;
}
for (int i = 0; i < text.Length; i++)
{
totalBytes = totalBytes % bufferWidth;
if (!afterLastToken)
{
// Figure out the color of the character - if it's in a token,
// use the tokens color otherwise use the initial color.
var state = tokenStack.Peek();
var token = state.Tokens[state.Index];
if (i == token.Extent.EndOffset)
{
if (token == state.Tokens[state.Tokens.Length - 1])
{
tokenStack.Pop();
if (tokenStack.Count == 0)
{
afterLastToken = true;
token = null;
foregroundColor = _initialForegroundColor;
backgroundColor = _initialBackgroundColor;
}
else
{
state = tokenStack.Peek();
}
}
if (!afterLastToken)
{
foregroundColor = state.ForegroundColor;
backgroundColor = state.BackgroundColor;
token = state.Tokens[++state.Index];
}
}
if (!afterLastToken && i == token.Extent.StartOffset)
{
GetTokenColors(token, out foregroundColor, out backgroundColor);
var stringToken = token as StringExpandableToken;
if (stringToken != null)
{
// We might have nested tokens.
if (stringToken.NestedTokens != null && stringToken.NestedTokens.Any())
{
var tokens = new Token[stringToken.NestedTokens.Count + 1];
stringToken.NestedTokens.CopyTo(tokens, 0);
// NestedTokens doesn't have an "EOS" token, so we use
// the string literal token for that purpose.
tokens[tokens.Length - 1] = stringToken;
tokenStack.Push(new SavedTokenState
{
Tokens = tokens,
//.........这里部分代码省略.........
开发者ID:cybernetics,项目名称:PSReadLine,代码行数:101,代码来源:Render.cs
示例20: IsTokenTheSame
private static bool IsTokenTheSame(Token x, Token y)
{
if (x.Kind == y.Kind && x.TokenFlags == y.TokenFlags &&
x.Extent.StartLineNumber == y.Extent.StartLineNumber &&
x.Extent.StartColumnNumber == y.Extent.StartColumnNumber &&
x.Extent.EndLineNumber == y.Extent.EndLineNumber &&
x.Extent.EndColumnNumber == y.Extent.EndColumnNumber)
{
return true;
}
return false;
}
开发者ID:dfinke,项目名称:powershell,代码行数:13,代码来源:CompletionAnalysis.cs
注:本文中的System.Management.Automation.Language.Token类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论