private Expr ParseSingleExpression() { if (this.index == this.tokens.Count) { throw new System.Exception("expected expression, got EOF"); } if (this.tokens[this.index] is Text.StringBuilder) { string value = ((Text.StringBuilder) this.tokens[this.index++]).ToString(); StringLiteral stringLiteral = new StringLiteral(); stringLiteral.Value = value; return(stringLiteral); } else if (this.tokens[this.index] is int) { int intValue = (int)this.tokens[this.index++]; IntLiteral intLiteral = new IntLiteral(); intLiteral.Value = intValue; return(intLiteral); } else if (this.tokens[this.index] is string) { string ident = (string)this.tokens[this.index++]; Variable var = new Variable(); var.Ident = ident; return(var); } else { throw new System.Exception("expected string literal, int literal, or variable"); } }
public IErrorReporter ErrorSlicingOnDereference() { NameResolver resolver = null; foreach (var mutability in Options.AllMutabilityModes) { var env = Environment.Create(new Options() { AllowDereference = true }.SetMutability(mutability)); var root_ns = env.Root; Int64Literal rhs_value = IntLiteral.Create("80"); root_ns.AddBuilder(FunctionBuilder.Create( "foo", null, ExpressionReadMode.OptionalUse, NameFactory.UnitNameReference(), Block.CreateStatement( VariableDeclaration.CreateStatement("p", NameFactory.PointerNameReference(NameFactory.IObjectNameReference(TypeMutability.Reassignable)), Undef.Create()), // only with same type we have guarantee we won't use dereference as slicing tool, consider // x *Object ; (*x) = big_type_instance Assignment.CreateStatement(Dereference.Create(NameReference.Create("p")), rhs_value) ))); resolver = NameResolver.Create(env); Assert.AreEqual(1, resolver.ErrorManager.Errors.Count); Assert.IsTrue(resolver.ErrorManager.HasError(ErrorCode.TypeMismatch, rhs_value)); } return(resolver); }
//<expr-primary><--<int>// public string Visit(IntLiteral node) { var sb = new StringBuilder(); var thisInt = node.AnchorToken.Lexeme; if (thisInt[0].Equals('+') || thisInt[0].Equals('-')) { var nosignint = thisInt.Substring(1); if (thisInt[0].Equals('-')) { sb.Append("\t\tldc.i4.0\n"); sb.Append("\t\tldc.i4 " + Int32.Parse(nosignint) + "\n"); sb.Append("\t\tsub.ovf\n"); } else { sb.Append("\t\tldc.i4 " + Int32.Parse(nosignint) + "\n"); } } else { sb.Append("\t\tldc.i4 " + Int32.Parse(thisInt) + "\n"); } return(sb.ToString()); }
public override void Visit(IntLiteral node) { PushLocation(node); _ilGen.Ldc_I4((int)node.Value); _result.ValueType = mdr.ValueTypes.Int32; PopLocation(); }
private Expr ParseSimpleExpr() { if (_index == _tokens.Count()) { throw new Exception("expected expression, got EOF"); } if (_tokens.ElementAt(_index) is StringBuilder) { var value = _tokens.ElementAt(_index++).ToString(); var stringLiteral = new StringLiteral(value); return(stringLiteral); } if (_tokens.ElementAt(_index) is int) { var intValue = (int)_tokens.ElementAt(_index++); var intLiteral = new IntLiteral(intValue); return(intLiteral); } if (_tokens.ElementAt(_index) is string) { var ident = (string)_tokens.ElementAt(_index++); var var = new Variable(ident); return(var); } throw new Exception("expected string literal, int literal, or variable"); }
private Expr ParseExpr() { if (this.index == this.tokens.Count) { throw new System.Exception("expected expression, got EOF"); } if (this.tokens[this.index] is Text.StringBuilder) { string value = ((Text.StringBuilder)this.tokens[this.index++]).ToString(); StringLiteral stringLiteral = new StringLiteral(); stringLiteral.Value = value; return stringLiteral; } else if (this.tokens[this.index] is int) { int intValue = (int)this.tokens[this.index++]; IntLiteral intLiteral = new IntLiteral(); intLiteral.Value = intValue; return intLiteral; } else if (this.tokens[this.index] is string) { string ident = (string)this.tokens[this.index++]; Variable var = new Variable(); var.Ident = ident; return var; } else { throw new System.Exception("expected string literal, int literal, or variable"); } }
public void parsesLiterals() { Parser p = new Parser(); Token a = new IntLiteral("0"); Token b = new StringLiteral(""); Token c = new BoolLiteral(""); Token s = new NonTerminal("s"); List <Token> production = new List <Token>(); production.Add(a); production.Add(b); production.Add(c); p.addProduction(s, production); p.setStartSymbol(s); p.prepareForParsing(); List <Token> parseThese = new List <Token>(); parseThese.Add(new IntLiteral("-50")); parseThese.Add(new StringLiteral("abc")); parseThese.Add(new BoolLiteral("true")); SyntaxTree parsed = p.parse(parseThese); Assert.AreEqual(new IntLiteral("-50"), parsed.root.children[0].token); Assert.AreNotEqual(new IntLiteral("50"), parsed.root.children[0].token); Assert.AreEqual(new StringLiteral("abc"), parsed.root.children[1].token); Assert.AreNotEqual(new StringLiteral("def"), parsed.root.children[1].token); Assert.AreEqual(new BoolLiteral("true"), parsed.root.children[2].token); Assert.AreNotEqual(new BoolLiteral("false"), parsed.root.children[2].token); }
public override Unit VisitIntLiteral(IntLiteral literal) { if (code.PushOnStack) { //cargando el entero para la pila code.Method.GetILGenerator().Emit(OpCodes.Ldc_I4, literal.Value); } return(Unit.Create()); }
public Type Visit(IntLiteral node) { var intStr = node.AnchorToken.Lexeme; try { Convert.ToInt32(intStr); }catch (OverflowException) { throw new SemanticError("Integer literal exceeds 32 bits (too large): " + intStr, node.AnchorToken); } return(Type.INT); }
public void Visit(IntLiteral node) { var intStr = node.AnchorToken.Lexeme; try { Convert.ToInt32(intStr); } catch (OverflowException) { throw new SemanticError("Integer literal too large: " + intStr, node.AnchorToken); } }
// Literals // Integer literal private void WriteIntegerLiteral(IntLiteral intLiteral) { if (IsPowerOfTwo(intLiteral.Value) && intLiteral.Value >= 16) { WriteHexIntegerLiteral(intLiteral.Value); } else { Write(intLiteral.Value.ToString()); } }
//----------------------------------------------------------- public void Visit(IntLiteral node) { var number = node.AnchorToken.Lexeme; try { Convert.ToInt32(number); } catch (OverflowException) { throw new SemanticError("Value was either too large or too small for an Int32."); } }
public void Visit(IntLiteral node) { var intStr = node.AnchorToken.Lexeme; int value; if (!Int32.TryParse(intStr, out value)) { throw new SemanticError( $"Integer literal too large: {intStr}", node.AnchorToken); } }
public string Visit(IntLiteral node) { var value = Convert.ToInt32(node.AnchorToken.Lexeme); if (value <= 127) { return("\tldc.i4.s " + value + "\n"); } else { return("\tldc.i4 " + value + "\n"); } }
public IErrorReporter ErrorEscapingReceivedReferenceFromFunction() { NameResolver resolver = null; foreach (var mutability in Options.AllMutabilityModes) { var env = Language.Environment.Create(new Options() { DiscardingAnyExpressionDuringTests = true } .SetMutability(mutability)); var root_ns = env.Root; root_ns.AddBuilder(FunctionBuilder.Create("selector", ExpressionReadMode.ReadRequired, NameFactory.ReferenceNameReference(NameFactory.IntNameReference()), Block.CreateStatement( ExpressionFactory.Readout("b"), Return.Create(NameReference.Create("a")) )) .Parameters( FunctionParameter.Create("a", NameFactory.ReferenceNameReference(NameFactory.IntNameReference())), FunctionParameter.Create("b", NameFactory.ReferenceNameReference(NameFactory.IntNameReference())))); FunctionCall call = FunctionCall.Create("selector", IntLiteral.Create("2"), IntLiteral.Create("3")); FunctionDefinition func = root_ns.AddBuilder(FunctionBuilder.Create("notimportant", ExpressionReadMode.OptionalUse, NameFactory.UnitNameReference(), Block.CreateStatement( VariableDeclaration.CreateStatement("h", NameFactory.ReferenceNameReference(NameFactory.IntNameReference()), IntLiteral.Create("0"), EntityModifier.Reassignable), Block.CreateStatement( // error: the most alive reference the function can return is limited to this scope // so it cannot be assigned to outer-scope variable Assignment.CreateStatement(NameReference.Create("h"), call) ), ExpressionFactory.Readout("h") ))); resolver = NameResolver.Create(env); Assert.AreEqual(1, resolver.ErrorManager.Errors.Count); Assert.IsTrue(resolver.ErrorManager.HasError(ErrorCode.EscapingReference, call)); } return(resolver); }
//----------------------------------------------------------- //<expr-primary><--<int>// public void Visit(IntLiteral node, char i) { var thisIntString = node.AnchorToken.Lexeme; char charChar = thisIntString[0]; if (charChar.Equals('-') || charChar.Equals('+')) { if (charChar.Equals('-')) { try { var oneInt = Int32.Parse(thisIntString.Substring(1)); oneInt = 0 - oneInt - 1; Int32.Parse(oneInt.ToString()); } catch (System.Exception) { throw new SemanticError( "Int value too big: " + node.AnchorToken.Lexeme, node.AnchorToken); } } else { try { Int32.Parse(thisIntString.Substring(1)); } catch (System.Exception) { throw new SemanticError( "Int value too big: " + node.AnchorToken.Lexeme, node.AnchorToken); } } } else { try { Int32.Parse(thisIntString); } catch (System.Exception) { throw new SemanticError( "Int value too big: " + node.AnchorToken.Lexeme, node.AnchorToken); } } }
//check public string Visit(IntLiteral node) { var intValue = Convert.ToInt32(node.AnchorToken.Lexeme); if (intValue <= 8) { return(putS(Indentar() + "ldc.i4." + intValue)); } else if (intValue <= 127) { return(putS(Indentar() + "ldc.i4.s " + intValue)); } return(putS(Indentar() + "ldc.i4 " + intValue)); }
private Token ExtractLiteral(IToken token) { string text = token.Text; TextSpan textSpan = token.GetTextSpan(); Token result = null; try { if (text.StartsWith("@")) { result = new IdToken(text.Substring(1), textSpan); } else if (text.StartsWith("\"") || text.StartsWith("[")) { result = new IdToken(text.Substring(1, text.Length - 2), textSpan); } else if (text.EndsWith("'")) { if (text.StartsWith("N")) { text = text.Substring(1); } text = text.Substring(1, text.Length - 2); result = new StringLiteral(text, textSpan); } else if (text.All(c => char.IsDigit(c))) { result = new IntLiteral(long.Parse(text), textSpan); } else if (text.StartsWith("0X", StringComparison.OrdinalIgnoreCase)) { result = new IntLiteral(System.Convert.ToInt64(text.Substring(2), 16), textSpan); } else if (double.TryParse(text, out double floatValue)) { result = new FloatLiteral(floatValue, textSpan); } } catch { } if (result == null && (text.Any(c => char.IsLetterOrDigit(c) || c == '_'))) { result = new IdToken(text, textSpan); } return(result); }
private Token ExtractLiteral(IToken token) { string text = token.Text; TextSpan textSpan = token.GetTextSpan(); Token result; double floatValue; if (text.StartsWith("@")) { result = new IdToken(text.Substring(1), textSpan, FileNode); } else if (text.StartsWith("\"") || text.StartsWith("[")) { result = new IdToken(text.Substring(1, text.Length - 2), textSpan, FileNode); } else if (text.EndsWith("'")) { if (text.StartsWith("N")) { text = text.Substring(1); } text = text.Substring(1, text.Length - 2); result = new StringLiteral(text, textSpan, FileNode); } else if (text.All(c => char.IsDigit(c))) { result = new IntLiteral(long.Parse(text), textSpan, FileNode); } else if (text.StartsWith("0X") || text.StartsWith("0x")) { result = new IntLiteral(Convert.ToInt64(text.Substring(2), 16), textSpan, FileNode); } else if (double.TryParse(text, out floatValue)) { result = new FloatLiteral(floatValue, textSpan, FileNode); } else { if (text.Any(c => char.IsLetterOrDigit(c) || c == '_')) { result = new IdToken(text, textSpan, FileNode); } else { result = null; } } return(result); }
public override Evaluation Analyze(StringLiteralDereferenceEx node, Analyzer analyzer, ExInfoFromParent info) { access = info.Access; node.StringExpr = node.StringExpr.Analyze(analyzer, info).Literalize(); node.KeyExpr = node.KeyExpr.Analyze(analyzer, info).Literalize(); IntLiteral @int = node.KeyExpr as IntLiteral; if (@int != null) { int key = (int)@int.Value; if (key >= 0) { StringLiteral str; BinaryStringLiteral bstr; if ((str = node.StringExpr as StringLiteral) != null) { string strValue = (string)str.Value; if (key < strValue.Length) { return(new Evaluation(node, strValue[key].ToString())); } else { } // report invalid index } else if ((bstr = node.StringExpr as BinaryStringLiteral) != null) { var bytesValue = (PhpBytes)bstr.GetValue(); if (key < bytesValue.Length) { return(new Evaluation(node, new PhpBytes(new byte[] { bytesValue[key] }))); } else { } // report invalid index } } else { // report invalid index } } return(new Evaluation(node)); }
//----------------------------------------------------------- public Type Visit(IntLiteral node) { var intStr = node.AnchorToken.Lexeme; try { Convert.ToInt32(intStr); } catch (OverflowException) { throw new SemanticError( "Integer literal too large to fit in memory: " + intStr, node.AnchorToken); } return(Type.INTEGER); }
public static LispLiteral Add(Context context, params LispLiteral[] args) { var evaluatedArgs = EvalArgs(context, args.ToList()); if (evaluatedArgs.Count != 2) { throw new LispPrimitiveBadArgNumber("ADD", 1, evaluatedArgs.Count); } var v1 = evaluatedArgs[0] as LispLiteral; var v2 = evaluatedArgs[1] as LispLiteral; var t1 = v1.Type; var t2 = v2.Type; if (!v1.IsNumericType) { throw new LispPrimitiveBadArgType("ADD", 1, LispValueType.Numeric, t1); } if (!v2.IsNumericType) { throw new LispPrimitiveBadArgType("ADD", 1, LispValueType.Numeric, t2); } var resultType = t1 == LispValueType.Double || t2 == LispValueType.Double ? LispValueType.Double : LispValueType.Int; LispLiteral result = null; if (resultType == LispValueType.Double) { result = new DoubleLiteral(v1.DoubleValue + v2.DoubleValue); } else if (resultType == LispValueType.Int) { result = new IntLiteral(v1.IntValue + v2.IntValue); } else { result = NilLiteral.Instance; } return(result); }
public static Literal /*!*/ Create(Text.Span position, object value, AccessType access) { Literal result; if (value == null) { result = new NullLiteral(position); } else if (value.GetType() == typeof(int)) { result = new IntLiteral(position, (int)value); } else if (value.GetType() == typeof(string)) { result = new StringLiteral(position, (string)value); } else if (value.GetType() == typeof(bool)) { result = new BoolLiteral(position, (bool)value); } else if (value.GetType() == typeof(double)) { result = new DoubleLiteral(position, (double)value); } else if (value.GetType() == typeof(long)) { result = new LongIntLiteral(position, (long)value); } else if (value.GetType() == typeof(PhpBytes)) { result = new BinaryStringLiteral(position, ((PhpBytes)value).ReadonlyData); } else { throw new ArgumentException("value"); } // Debug.Assert(result != null); result.NodeCompiler <IExpressionCompiler>().Access = access; // return(result); }
public UstNode VisitLiteral(DslParser.LiteralContext context) { Token result; var textSpan = context.GetTextSpan(); if (context.Id() != null) { result = ProcessId(context.Id()); } else if (context.String() != null) { result = new StringLiteral(RemoveQuotes(context.GetText()), textSpan, null); } else if (context.Oct() != null) { result = new IntLiteral( System.Convert.ToInt64(context.Oct().GetText(), 8), textSpan, null); } else if (context.Int() != null) { result = new IntLiteral(long.Parse(context.Int().GetText()), textSpan, null); } else if (context.Hex() != null) { result = new IntLiteral( System.Convert.ToInt64(context.Hex().GetText(), 16), textSpan, null); } else if (context.Bool() != null) { result = new BooleanLiteral(bool.Parse(context.Bool().GetText()), textSpan, null); } else if (context.Null() != null) { result = new NullLiteral(textSpan, null); } else { throw new NotImplementedException(); } return(result); }
/// <returns><see cref="Token"/></returns> public override UstNode VisitTerminal(ITerminalNode node) { string text = node.GetText(); TextSpan textSpan = node.GetTextSpan(); Token result; double doubleResult; if (text.StartsWith("'")) { result = new StringLiteral(text.Substring(1, text.Length - 2), textSpan, FileNode); } else if (text.ToLowerInvariant().StartsWith("n'")) { result = new StringLiteral(text.Substring(2, text.Length - 3), textSpan, FileNode); } else if (text.All(c => char.IsDigit(c))) { result = new IntLiteral(long.Parse(text), textSpan, FileNode); } else if (double.TryParse(text, out doubleResult)) { result = new FloatLiteral(doubleResult, textSpan, FileNode); } else if (text.All(c => char.IsLetterOrDigit(c) || c == '_')) { result = new IdToken(text, textSpan, FileNode); } else { if (text.Any(c => char.IsLetterOrDigit(c) || c == '_')) { Logger.LogDebug($"{text} converter to IdToken"); result = new IdToken(text, textSpan, FileNode); } else { result = null; } } return(result); }
Expression PrimaryExpression() { if (Current.TokenKind == TokenKind.StringStart) { return(ReadString()); } else if (Current.TokenKind == TokenKind.ID) { Token id = Consume(); if (Current.TokenKind == TokenKind.LParen) { Consume(); // consume LParen Expression[] args = ReadArguments(); Consume(TokenKind.RParen); return(new FCall(id.Line, id.Col, id.Data, args)); } else if (Current.TokenKind == TokenKind.Dot) { Consume(); Token field = Consume(TokenKind.ID); return(new FieldAccess(id.Line, id.Col, id.Data, field.Data)); } else { return(new Name(id.Line, id.Col, id.Data)); } } else if (Current.TokenKind == TokenKind.Integer) { int value = Int32.Parse(Current.Data); IntLiteral intLiteral = new IntLiteral(Current.Line, Current.Col, value); Consume(); // consume int return(intLiteral); } else { throw new ParseException("Invalid token in expression: " + Current.TokenKind + ". Was expecting ID or string.", Current.Line, Current.Col); } }
public UstNode VisitPatternIntExpression([NotNull] DslParser.PatternIntExpressionContext context) { IntLiteral result; if (context.op != null) { long leftValue = ((IntLiteral)VisitPatternIntExpression(context.left)).Value; long rightValue = ((IntLiteral)VisitPatternIntExpression(context.right)).Value; long resultValue = 0; switch (context.op.Text) { case "*": resultValue = leftValue * rightValue; break; case "/": resultValue = leftValue / rightValue; break; case "+": resultValue = leftValue + rightValue; break; case "-": resultValue = leftValue - rightValue; break; default: throw new NotImplementedException($"Operation {context.op.Text} is not implemented"); } result = new IntLiteral(resultValue, context.GetTextSpan(), null); } else { result = (IntLiteral)VisitPatternInt(context.patternInt()); } return(result); }
// the sections mentioned in comments of this method are from C# specification v1.2 public static Conversion GetImplicit(Operand op, Type to, bool onlyStandard, ITypeMapper typeMapper) { Type from = Operand.GetType(op, typeMapper); Type toUnderlying = Helpers.GetNullableUnderlyingType(to); if (to.Equals(from)) { return(new Direct(typeMapper)); } Type fromUnderlying = Helpers.GetNullableUnderlyingType(@from); if (toUnderlying != null) { if (fromUnderlying != null) { Conversion c = GetImplicit(new FakeTypedOperand(fromUnderlying), toUnderlying, onlyStandard, typeMapper); if (c.IsValid) { return(new ConvertNullable(typeMapper, c)); } } else { Conversion c = GetImplicit(op, toUnderlying, onlyStandard, typeMapper); if (c.IsValid) { return(new WrapNullable(typeMapper, c)); } } } // required for arrays created from TypeBuilder-s if (from != null && to.IsArray && from.IsArray) { if (to.GetArrayRank() == from.GetArrayRank()) { if (to.GetElementType().Equals(from.GetElementType())) { return(new Direct(typeMapper)); } } } TypeCode tcFrom = Type.GetTypeCode(from); TypeCode tcTo = Type.GetTypeCode(to); byte ct = _convTable[(int)tcFrom][(int)tcTo]; // section 6.1.2 - Implicit numeric conversions if (from != null && (from.IsPrimitive || Helpers.AreTypesEqual(from, typeof(decimal), typeMapper)) && (to.IsPrimitive || Helpers.AreTypesEqual(to, typeof(decimal), typeMapper))) { if (ct <= I) { if (Helpers.AreTypesEqual(from, typeof(decimal), typeMapper) || Helpers.AreTypesEqual(to, typeof(decimal), typeMapper)) { // decimal is handled as user-defined conversion, but as it is a standard one, always enable UDC processing onlyStandard = false; } else { return(new Primitive(typeMapper)); } } } IntLiteral intLit = op as IntLiteral; // section 6.1.3 - Implicit enumeration conversions if (!onlyStandard && to.IsEnum && (object)intLit != null && intLit.Value == 0) { return(new Primitive(typeMapper)); } // section 6.1.4 - Implicit reference conversions if ((from == null || !from.IsValueType) && !to.IsValueType) { if (from == null) // from the null type to any reference type { return(new Direct(typeMapper)); } if (to.IsAssignableFrom(from)) // the rest { return(new Direct(typeMapper)); } } if (from == null) // no other conversion from null type is possible { return(new Invalid(typeMapper)); } // section 6.1.5 - Boxing conversions if (from.IsValueType) { if (to.IsAssignableFrom(from)) { return(new Boxing(typeMapper)); } } // section 6.1.6 - Implicit constant expression conversions if ((object)intLit != null && Helpers.AreTypesEqual(from, typeof(int), typeMapper) && to.IsPrimitive) { int val = intLit.Value; switch (tcTo) { case TypeCode.SByte: if (val >= sbyte.MinValue && val <= sbyte.MaxValue) { return(new Direct(typeMapper)); } break; case TypeCode.Byte: if (val >= byte.MinValue && val <= byte.MaxValue) { return(new Direct(typeMapper)); } break; case TypeCode.Int16: if (val >= short.MinValue && val <= short.MaxValue) { return(new Direct(typeMapper)); } break; case TypeCode.UInt16: if (val >= ushort.MinValue && val <= ushort.MaxValue) { return(new Direct(typeMapper)); } break; case TypeCode.UInt32: if (val >= 0) { return(new Direct(typeMapper)); } break; case TypeCode.UInt64: if (val >= 0) { return(new Direct(typeMapper)); } break; } } // section 6.1.7 - User-defined implicit conversions (details in section 6.4.3) if (onlyStandard || Helpers.AreTypesEqual(from, typeof(object), typeMapper) || Helpers.AreTypesEqual(to, typeof(object), typeMapper) || from.IsInterface || to.IsInterface || to.IsSubclassOf(from) || from.IsSubclassOf(to)) { return(new Invalid(typeMapper)); // skip not-permitted conversion attempts (section 6.4.1) } List <UserDefined> candidates = null; FindCandidates(ref candidates, FindImplicitMethods(from, to, typeMapper), op, to, GetImplicit, typeMapper); if (candidates == null) { return(new Invalid(typeMapper)); } if (candidates.Count == 1) { return(candidates[0]); } return(UserDefined.FindImplicit(candidates, @from, to, typeMapper)); }
public CodeExpression VisitIntLiteral(IntLiteral i) { return(m.Number(i.Value)); }
public VariableModifier(VariableModifierKind kind, IntLiteral index) { Kind = kind; Index = index; }
public void Visit(IntLiteral il) { _instructions.Add(Instruction.Create(OpCodes.Ldc_I4, il.Value)); }
public void Visit(IntLiteral il) { _sb.Append(il.Value); }
private TreeNode IntegerUpdate(TreeNode [] args, int value) { TreeNode variable_node = (FunctionNode)args[0]; TreeNode result = Evaluate(variable_node); TreeNode new_result = new IntLiteral(((IntLiteral)result).Value + value); FunctionFunctionSet.VariableSet(Evaluator, args[0], new_result); return new_result; }
public void VisitIntLiteral(IntLiteral s) { throw new NotImplementedException(); }
public void Visit(IntLiteral il) { // Nothing to do here... }
/// <summary> /// Looks for address, given an int literal. /// </summary> /// <returns>The address to look for.</returns> /// <param name="intLit">The literal holding the integer.</param> public Variable LookForAddress(IntLiteral intLit) { return this.LookForAddress( intLit.Value ); }
static string Example6() { AtomExprList ael1 = new AtomExprList(); Call c1 = new Call("foo", ael1); CallStmt cs1 = new CallStmt(c1); NumLiteral n1 = new NumLiteral(3.14); TmpNumReg tnr0 = new TmpNumReg(0); Assign a1 = new Assign(tnr0, n1); TmpIntReg tir0 = new TmpIntReg(0); IntLiteral i1 = new IntLiteral(42); StringLiteral s1 = new StringLiteral("hi"); AtomExprList ael2 = new AtomExprList(); ael2.Add(tir0); ael2.Add(i1); ael2.Add(s1); Call c2 = new Call("bar", ael2); CallStmt cs2 = new CallStmt(c2); NamedReg a = new NamedReg("a"); LocalDecl ld1 = new LocalDecl(new IntType(), a); NamedReg b = new NamedReg("b"); LocalDecl ld2 = new LocalDecl(new NumType(), b); NamedReg c = new NamedReg("c"); LocalDecl ld3 = new LocalDecl(new StringType(), c); TmpNumReg tnr2 = new TmpNumReg(2); NumLiteral n2 = new NumLiteral(2.7); Assign a2 = new Assign(tnr2, n2); StringLiteral s2 = new StringLiteral("hello yourself"); AtomExprList ael3 = new AtomExprList(); ael3.Add(tnr2); ael3.Add(s2); Call c3 = new Call("baz", ael3); RegList rl4 = new RegList(); rl4.Add(a); rl4.Add(b); rl4.Add(c); Assign a3 = new Assign(rl4, c3); StmtList sl1 = new StmtList(); sl1.Add(cs1); sl1.Add(a1); sl1.Add(cs2); sl1.Add(ld1); sl1.Add(ld2); sl1.Add(ld3); sl1.Add(a2); sl1.Add(a3); Sub main = new Sub("main", sl1); StringLiteral s3 = new StringLiteral("Foo!\n"); Call c4 = new Call("print", s3); CallStmt cs3 = new CallStmt(c4); StmtList sl2 = new StmtList(); sl2.Add(cs3); Sub foo = new Sub("foo", sl2); NamedReg i = new NamedReg("i"); ParamDecl pd1 = new ParamDecl(new NumType(), i); NamedReg answer = new NamedReg("answer"); ParamDecl pd2 = new ParamDecl(new IntType(), answer); NamedReg message = new NamedReg("message"); ParamDecl pd3 = new ParamDecl(new StringType(), message); StringLiteral s4 = new StringLiteral("Bar!\n"); Call print1 = new Call("print", s4); CallStmt cs4 = new CallStmt(print1); Call print2 = new Call("print", i); CallStmt cs5 = new CallStmt(print2); StringLiteral s5 = new StringLiteral("\n"); Call print3 = new Call("print", s5); CallStmt cs6 = new CallStmt(print3); Call print4 = new Call("print", answer); CallStmt cs7 = new CallStmt(print4); CallStmt cs8 = new CallStmt(print3); Call print5 = new Call("print", message); CallStmt cs9 = new CallStmt(print5); StmtList sl3 = new StmtList(); sl3.Add(pd1); sl3.Add(pd2); sl3.Add(pd3); sl3.Add(cs4); sl3.Add(cs5); sl3.Add(cs6); sl3.Add(cs7); sl3.Add(cs8); sl3.Add(cs9); Sub bar = new Sub("bar", sl3); NamedReg e = new NamedReg("e"); ParamDecl pd4 = new ParamDecl(new NumType(), e); NamedReg msg = new NamedReg("msg"); ParamDecl pd5 = new ParamDecl(new StringType(), msg); StringLiteral s6 = new StringLiteral("Baz!\n"); Call print7 = new Call("print", s6); CallStmt cs10 = new CallStmt(print7); Call print8 = new Call("print", e); CallStmt cs11 = new CallStmt(print8); Call print9 = new Call("print", s5); CallStmt cs12 = new CallStmt(print9); Call print10 = new Call("print", msg); CallStmt cs13 = new CallStmt(print10); AtomExprList ael4 = new AtomExprList(); ael4.Add(new IntLiteral(1000)); ael4.Add(new NumLiteral(1.23)); ael4.Add(new StringLiteral("hi from baz")); ReturnStmt rs1 = new ReturnStmt(ael4); StmtList sl4 = new StmtList(); sl4.Add(pd4); sl4.Add(pd5); sl4.Add(cs10); sl4.Add(cs11); sl4.Add(cs12); sl4.Add(cs13); sl4.Add(rs1); Sub baz = new Sub("baz", sl4); Pirate p = new Pirate(); p.Add(main); p.Add(foo); p.Add(bar); p.Add(baz); StringWriter sw = new StringWriter(); PirateWriter pv = new PirateWriter(sw); DynamicVisitor.accept(p, pv); return sw.ToString(); }
private void TokenPush(bool as_string) { if(current_token.Length == 0 && !as_string) { return; } TreeNode node = null; string token = current_token.ToString(); if(Debug) { Console.Write("{3}[{0}] TOKEN({4},{5}): [{2}{1}{2}]", scope, token, as_string ? "\"" : String.Empty, String.Empty.PadLeft(scope - 1, ' '), line, column - current_token.Length); } if(as_string) { node = new StringLiteral(token); } else if(token == "#t") { node = new BooleanLiteral(true); } else if(token == "#f") { node = new BooleanLiteral(false); } else if(token.Length > 0 && token != "." && token != "-" && token != "+" && number_regex.IsMatch(token)) { try { if(token.StartsWith("0x") || token.StartsWith("-0x")) { int offset = token[0] == '-' ? 3 : 2; int value = Int32.Parse(token.Substring(offset), NumberStyles.HexNumber, culture_info.NumberFormat); node = new IntLiteral(value * (offset == 3 ? -1 : 1)); } else if(token.Contains(".")) { node = new DoubleLiteral(Double.Parse(token, NumberStyles.Float, culture_info.NumberFormat)); } else { node = new IntLiteral(Int32.Parse(token, NumberStyles.Integer, culture_info.NumberFormat)); } } catch { throw new FormatException("Invalid number format: " + token); } } else { node = new FunctionNode(token); } if(Debug) { Console.WriteLine(" => [{0}]", node); } node.Line = line; node.Column = column; current_parent.AddChild(node); current_token.Remove(0, current_token.Length); }
private Expr ParseExpr() { if (this.indice == this.tokens.Count) { throw new System.Exception("Se esperaba una expresion, se llego al final del archivo"); } if (this.tokens[this.indice] is Text.StringBuilder) { string value = ((Text.StringBuilder)this.tokens[this.indice++]).ToString(); StringLiteral stringLiteral = new StringLiteral(); stringLiteral.Value = value; return stringLiteral; } //********* else if (this.tokens[this.indice + 1] == Scanner.Sum || this.tokens[this.indice + 1] == Scanner.Res || this.tokens[this.indice + 1] == Scanner.Mul || this.tokens[this.indice + 1] == Scanner.Div) { BinExpr binExpr = new BinExpr(); Expr left; if (this.tokens[this.indice] is int) { int intValue = (int)this.tokens[this.indice++]; IntLiteral intLiteral = new IntLiteral(); intLiteral.Value = intValue; left = intLiteral; } else if (this.tokens[this.indice] is string) { string ident = (string)this.tokens[this.indice++]; Variable var = new Variable(); var.Ident = ident; left = var; } else { throw new System.Exception("Se esperaba un entero o variable para la operacion."); } binExpr.Left = left; object op = this.tokens[this.indice++]; if (op == Scanner.Sum) binExpr.Op = BinOp.Sum; else if (op == Scanner.Res) binExpr.Op = BinOp.Res; else if (op == Scanner.Mul) binExpr.Op = BinOp.Mul; else if (op == Scanner.Div) binExpr.Op = BinOp.Div; binExpr.Right = this.ParseExpr(); return binExpr; } //********* else if (this.tokens[this.indice] is int) { int intValue = (int)this.tokens[this.indice++]; IntLiteral intLiteral = new IntLiteral(); intLiteral.Value = intValue; return intLiteral; } else if (this.tokens[this.indice] is string) { string ident = (string)this.tokens[this.indice++]; Variable var = new Variable(); var.Ident = ident; return var; } else { throw new System.Exception("se esperaba una cadena, entero o variable"); } }
public void Visit(IntLiteral il) { _result = il.Type = _intType; }
static string Example2() { NamedReg a = new NamedReg("a"); NamedReg b = new NamedReg("b"); NamedReg c = new NamedReg("c"); NamedReg det = new NamedReg("det"); IdList rl1 = new IdList(); rl1.Add(a); rl1.Add(b); rl1.Add(c); rl1.Add(det); LocalDecl ld1 = new LocalDecl(new NumType(), rl1); IntLiteral il3 = new IntLiteral(2); Assign a12 = new Assign(a, il3); IntLiteral il4 = new IntLiteral(-3); Assign a13 = new Assign(b, il4); IntLiteral il5 = new IntLiteral(-2); Assign a14 = new Assign(c, il5); UnaryNeg un1 = new UnaryNeg(b); TmpNumReg tnr0 = new TmpNumReg(0); Assign a1 = new Assign(tnr0, un1); TmpNumReg tnr1 = new TmpNumReg(1); BinaryMul bm1 = new BinaryMul(b, b); Assign a2 = new Assign(tnr1, bm1); TmpNumReg tnr2 = new TmpNumReg(2); IntLiteral il1 = new IntLiteral(4); BinaryMul bm2 = new BinaryMul(il1, a); Assign a3 = new Assign(tnr2, bm2); BinaryMul bm3 = new BinaryMul(tnr2, c); Assign a4 = new Assign(tnr2, bm3); TmpNumReg tnr3 = new TmpNumReg(3); IntLiteral il2 = new IntLiteral(2); BinaryMul bm4 = new BinaryMul(il2, a); Assign a5 = new Assign(tnr3, bm4); BinarySub bs1 = new BinarySub(tnr1, tnr2); Assign a6 = new Assign(det, bs1); TmpNumReg tnr4 = new TmpNumReg(4); Call sqrt = new Call("sqrt", det); Assign a7 = new Assign(tnr4, sqrt); NamedReg x1 = new NamedReg("x1"); NamedReg x2 = new NamedReg("x2"); IdList rl2 = new IdList(); rl2.Add(x1); rl2.Add(x2); LocalDecl ld2 = new LocalDecl(new NumType(), rl2); BinaryAdd ba1 = new BinaryAdd(tnr0, tnr4); Assign a8 = new Assign(x1, ba1); BinaryDiv bd1 = new BinaryDiv(x1, tnr3); Assign a9 = new Assign(x1, bd1); BinarySub bs2 = new BinarySub(tnr0, tnr4); Assign a10 = new Assign(x2, bs2); AssignDiv a11 = new AssignDiv(x2, tnr3); StringLiteral s1 = new StringLiteral("Answers to ABC formula are:\n"); Call c1 = new Call("print", s1); CallStmt print1 = new CallStmt(c1); StringLiteral s2 = new StringLiteral("x1 = "); Call c2 = new Call("print", s2); CallStmt print2 = new CallStmt(c2); Call c3 = new Call("print", x1); CallStmt print3 = new CallStmt(c3); StringLiteral s4 = new StringLiteral("\nx2 = "); Call c4 = new Call("print", s4); CallStmt print4 = new CallStmt(c4); Call c5 = new Call("print", x2); CallStmt print5 = new CallStmt(c5); StringLiteral s6 = new StringLiteral("\n"); Call c6 = new Call("print", s6); CallStmt print6 = new CallStmt(c6); StmtList sl1 = new StmtList(); sl1.Add(ld1); sl1.Add(a12); sl1.Add(a13); sl1.Add(a14); sl1.Add(a1); sl1.Add(a2); sl1.Add(a3); sl1.Add(a4); sl1.Add(a5); sl1.Add(a6); sl1.Add(a7); sl1.Add(ld2); sl1.Add(a8); sl1.Add(a9); sl1.Add(a10); sl1.Add(a11); sl1.Add(print1); sl1.Add(print2); sl1.Add(print3); sl1.Add(print4); sl1.Add(print5); sl1.Add(print6); Sub foo = new Sub("foo", sl1); Pirate p = new Pirate(); p.Add(foo); StringWriter sw = new StringWriter(); PirateWriter pv = new PirateWriter(sw); DynamicVisitor.accept(p, pv); return sw.ToString(); }
private Expr ParseSimpleExpr() { if (_index == _tokens.Count) throw new Exception("expected expression, got EOF"); if (_tokens[_index] is StringBuilder) { var value = _tokens[_index++].ToString(); var stringLiteral = new StringLiteral(value); return stringLiteral; } if (_tokens[_index] is int) { var intValue = (int)_tokens[_index++]; var intLiteral = new IntLiteral(intValue); return intLiteral; } if (_tokens[_index] is string) { var ident = (string)_tokens[_index++]; var var = new Variable(ident); return var; } throw new Exception("expected string literal, int literal, or variable"); }