public static VList<LNode> MaybeRemoveNoOpFromRunSeq(VList<LNode> runSeq)
		{
			// Delete final no-op in case of e.g. Foo()::id; => #runSequence(var id = Foo(); id)
			if (runSeq.Count > 1 && runSeq.Last.IsId)
				return runSeq.WithoutLast(1);
			return runSeq;
		}
Exemple #2
0
		/// <summary>Removes all existing trailing trivia from an attribute list and adds a new list of trailing trivia.</summary>
		/// <remarks>This method has a side-effect of recreating the #trivia_trailing
		/// node, if there is one, at the end of the attribute list. If <c>trivia</c>
		/// is empty then all calls to #trivia_trailing are removed.</remarks>
		public static VList<LNode> WithTrailingTrivia(this VList<LNode> attrs, VList<LNode> trivia)
		{
			var attrs2 = WithoutTrailingTrivia(attrs);
			if (trivia.IsEmpty)
				return attrs2;
			return attrs2.Add(LNode.Call(S.TriviaTrailing, trivia));
		}
		/// <summary>
		/// Selects a page of VIndividualDemographics objects from the database.
		/// </summary>
		private void Step_1_SelectAll_Generated()
		{
			int count = -1;
			mockCollection = DataRepository.VIndividualDemographicsProvider.GetPaged(null, 0, 10, out count);
			Assert.IsTrue(count >= 0, "Select Query Failed with GetPaged");
			System.Console.WriteLine("DataRepository.VIndividualDemographicsProvider.GetPaged():");			
			System.Console.WriteLine(mockCollection);			
		}
		/// <summary>
		/// Selects a page of VEmployeeDepartmentHistory objects from the database.
		/// </summary>
		private void Step_1_SelectAll_Generated()
		{
			int count = -1;
			mockCollection = DataRepository.VEmployeeDepartmentHistoryProvider.GetPaged(null, 0, 10, out count);
			Assert.IsTrue(count >= 0, "Select Query Failed with GetPaged");
			System.Console.WriteLine("DataRepository.VEmployeeDepartmentHistoryProvider.GetPaged():");			
			System.Console.WriteLine(mockCollection);			
		}
 /// <summary>
 /// Selects a page of ProductsAboveAveragePrice objects from the database.
 /// </summary>
 private void Step_1_SelectAll_Generated()
 {
     int count = -1;
     mockCollection = DataRepository.ProductsAboveAveragePriceProvider.GetPaged(null, 0, 10, out count);
     Assert.IsTrue(count >= 0, "Select Query Failed with GetPaged");
     System.Console.WriteLine("DataRepository.ProductsAboveAveragePriceProvider.GetPaged():");
     System.Console.WriteLine(mockCollection);
 }
 /// <summary>
 /// Selects a page of SummaryOfSalesByQuarter objects from the database.
 /// </summary>
 private void Step_1_SelectAll_Generated()
 {
     int count = -1;
     mockCollection = DataRepository.SummaryOfSalesByQuarterProvider.GetPaged(null, 0, 10, out count);
     Assert.IsTrue(count >= 0, "Select Query Failed with GetPaged");
     System.Console.WriteLine("DataRepository.SummaryOfSalesByQuarterProvider.GetPaged():");
     System.Console.WriteLine(mockCollection);
 }
 /// <summary>
 /// Selects a page of CustomerAndSuppliersByCity objects from the database.
 /// </summary>
 private void Step_1_SelectAll_Generated()
 {
     int count = -1;
     mockCollection = DataRepository.CustomerAndSuppliersByCityProvider.GetPaged(null, 0, 10, out count);
     Assert.IsTrue(count >= 0, "Select Query Failed with GetPaged");
     System.Console.WriteLine("DataRepository.CustomerAndSuppliersByCityProvider.GetPaged():");
     System.Console.WriteLine(mockCollection);
 }
		/// <summary>
		/// Convert a collection from the ws proxy to a nettiers collection.
		/// </summary>
		public static VList<VEmployeeDepartmentHistory> Convert(WsProxy.VEmployeeDepartmentHistory[] items)
		{
			VList<VEmployeeDepartmentHistory> outItems = new VList<VEmployeeDepartmentHistory>();
			foreach(WsProxy.VEmployeeDepartmentHistory item in items)
			{
				outItems.Add(Convert(item));
			}
			return outItems;
		}
		/// <summary>
		/// Convert a collection from the ws proxy to a nettiers collection.
		/// </summary>
		public static VList<VSalesPerson> Convert(WsProxy.VSalesPerson[] items)
		{
			VList<VSalesPerson> outItems = new VList<VSalesPerson>();
			foreach(WsProxy.VSalesPerson item in items)
			{
				outItems.Add(Convert(item));
			}
			return outItems;
		}
		/// <summary>
		/// Convert a collection from the ws proxy to a nettiers collection.
		/// </summary>
		public static VList<VSalesPersonSalesByFiscalYears> Convert(WsProxy.VSalesPersonSalesByFiscalYears[] items)
		{
			VList<VSalesPersonSalesByFiscalYears> outItems = new VList<VSalesPersonSalesByFiscalYears>();
			foreach(WsProxy.VSalesPersonSalesByFiscalYears item in items)
			{
				outItems.Add(Convert(item));
			}
			return outItems;
		}
		/// <summary>
		/// Convert a collection from the ws proxy to a nettiers collection.
		/// </summary>
		public static VList<VProductModelInstructions> Convert(WsProxy.VProductModelInstructions[] items)
		{
			VList<VProductModelInstructions> outItems = new VList<VProductModelInstructions>();
			foreach(WsProxy.VProductModelInstructions item in items)
			{
				outItems.Add(Convert(item));
			}
			return outItems;
		}
		/// <summary>
		/// Convert a collection from the ws proxy to a nettiers collection.
		/// </summary>
		public static VList<VAdditionalContactInfo> Convert(WsProxy.VAdditionalContactInfo[] items)
		{
			VList<VAdditionalContactInfo> outItems = new VList<VAdditionalContactInfo>();
			foreach(WsProxy.VAdditionalContactInfo item in items)
			{
				outItems.Add(Convert(item));
			}
			return outItems;
		}
		/// <summary>
		/// Convert a collection from the ws proxy to a nettiers collection.
		/// </summary>
		public static VList<VStateProvinceCountryRegion> Convert(WsProxy.VStateProvinceCountryRegion[] items)
		{
			VList<VStateProvinceCountryRegion> outItems = new VList<VStateProvinceCountryRegion>();
			foreach(WsProxy.VStateProvinceCountryRegion item in items)
			{
				outItems.Add(Convert(item));
			}
			return outItems;
		}
		/// <summary>
		/// Convert a collection from the ws proxy to a nettiers collection.
		/// </summary>
		public static VList<VIndividualCustomer> Convert(WsProxy.VIndividualCustomer[] items)
		{
			VList<VIndividualCustomer> outItems = new VList<VIndividualCustomer>();
			foreach(WsProxy.VIndividualCustomer item in items)
			{
				outItems.Add(Convert(item));
			}
			return outItems;
		}
		/// <summary>
		/// Convert a collection from the ws proxy to a nettiers collection.
		/// </summary>
		public static VList<VEmployee> Convert(WsProxy.VEmployee[] items)
		{
			VList<VEmployee> outItems = new VList<VEmployee>();
			foreach(WsProxy.VEmployee item in items)
			{
				outItems.Add(Convert(item));
			}
			return outItems;
		}
Exemple #16
0
			internal CodeGeneratorForMatchCase(IMacroContext context, LNode input, VList<LNode> handler)
			{
				_context = context;
				_input = input;
				_handler = handler;
				var @break = LNode.Call(CodeSymbols.Break);
				if (_handler.IsEmpty || !_handler.Last.Equals(@break))
					_handler.Add(@break);
			}
		/// <summary>
		/// Convert a collection from the ws proxy to a nettiers collection.
		/// </summary>
		public static VList<VJobCandidateEducation> Convert(WsProxy.VJobCandidateEducation[] items)
		{
			VList<VJobCandidateEducation> outItems = new VList<VJobCandidateEducation>();
			foreach(WsProxy.VJobCandidateEducation item in items)
			{
				outItems.Add(Convert(item));
			}
			return outItems;
		}
		/// <summary>
		/// Convert a collection from the ws proxy to a nettiers collection.
		/// </summary>
		public static VList<VIndividualDemographics> Convert(WsProxy.VIndividualDemographics[] items)
		{
			VList<VIndividualDemographics> outItems = new VList<VIndividualDemographics>();
			foreach(WsProxy.VIndividualDemographics item in items)
			{
				outItems.Add(Convert(item));
			}
			return outItems;
		}
		/// <summary>
		/// Convert a collection from the ws proxy to a nettiers collection.
		/// </summary>
		public static VList<VVendor> Convert(WsProxy.VVendor[] items)
		{
			VList<VVendor> outItems = new VList<VVendor>();
			foreach(WsProxy.VVendor item in items)
			{
				outItems.Add(Convert(item));
			}
			return outItems;
		}
		/// <summary>
		/// Convert a collection from the ws proxy to a nettiers collection.
		/// </summary>
		public static VList<VJobCandidateEmployment> Convert(WsProxy.VJobCandidateEmployment[] items)
		{
			VList<VJobCandidateEmployment> outItems = new VList<VJobCandidateEmployment>();
			foreach(WsProxy.VJobCandidateEmployment item in items)
			{
				outItems.Add(Convert(item));
			}
			return outItems;
		}
		/// <summary>
		/// Convert a collection from the ws proxy to a nettiers collection.
		/// </summary>
		public static VList<VProductAndDescription> Convert(WsProxy.VProductAndDescription[] items)
		{
			VList<VProductAndDescription> outItems = new VList<VProductAndDescription>();
			foreach(WsProxy.VProductAndDescription item in items)
			{
				outItems.Add(Convert(item));
			}
			return outItems;
		}
		protected override void WriteOutput(InputOutput io)
		{
			Results = io.Output;
			Output = new StringBuilder();
			foreach (LNode node in Results) {
				LNode.Printer(node, Output, Sink, null, IndentString, NewlineString);
				Output.Append(NewlineString);
			}
		}
Exemple #23
0
		public VList<LNode> ExprList(ref TokenType endMarker, VList<LNode> list = default(VList<LNode>))
		{
			TT la0;
			LNode e = default(LNode);
			Token end = default(Token);
			// line 57
			if ((LT0.Value is string)) {
				endMarker = TT.EOF;
			}
			// Line 1: ( / TopExpr)
			switch ((TT) LA0) {
			case EOF:
			case TT.Comma:
			case TT.Dedent:
			case TT.RBrace:
			case TT.RBrack:
			case TT.RParen:
			case TT.Semicolon:
				{
				}
				break;
			default:
				e = TopExpr();
				break;
			}
			// Line 59: ((TT.Comma|TT.Semicolon) ( / TopExpr))*
			for (;;) {
				la0 = (TT) LA0;
				if (la0 == TT.Comma || la0 == TT.Semicolon) {
					end = MatchAny();
					list.Add(e ?? MissingExpr());
					CheckEndMarker(ref endMarker, ref end);
					// Line 62: ( / TopExpr)
					switch ((TT) LA0) {
					case EOF:
					case TT.Comma:
					case TT.Dedent:
					case TT.RBrace:
					case TT.RBrack:
					case TT.RParen:
					case TT.Semicolon:
						// line 62
						e = null;
						break;
					default:
						e = TopExpr();
						break;
					}
				} else
					break;
			}
			if ((e != null || end.Type() == TT.Comma)) {
				list.Add(e ?? MissingExpr());
			}
			return list;
		}
		/// <summary>
		/// Searches some VIndividualCustomer objects from the database.
		/// </summary>
		private void Step_2_Search_Generated()
		{
			int count = -1;
			mockCollection = DataRepository.VIndividualCustomerProvider.Find(null, null, "", 0, 10, out count);
			Assert.IsTrue(count >= 0 && mockCollection != null, "Query Failed to issue Find Command.");
			
			System.Console.WriteLine("DataRepository.VIndividualCustomerProvider.Find():");			
			System.Console.WriteLine(mockCollection);
					
		}
		public static LNode AddCsLineDirectives(LNode node, IMacroContext context)
		{
			if (node.ArgCount != 0)
				return null;
			int sourceLine = -1;
			var list0 = new VList<LNode>(context.RemainingNodes);
			var list1 = context.PreProcess(list0);
			var list2 = AddLineDirectives(list1, true, ref sourceLine);
			context.DropRemainingNodes = true;
			return F.Call(S.Splice, list2);
		}
Exemple #26
0
		public static LNode unroll(LNode var, VList<LNode> cases, LNode body, IMessageSink sink)
		{
			// Maps identifiers => replacements. The integer counts how many times replacement occurred.
			var replacements = InternalList<Triplet<Symbol, LNode, int>>.Empty;
			if (var.IsId && !var.HasPAttrs()) {
				replacements.Add(Pair.Create(var.Name, (LNode)LNode.Missing, 0));
			} else {
				var vars = var.Args;
				if ((var.Calls(S.Tuple) || var.Calls(S.Braces)) && vars.All(a => a.IsId && !a.HasPAttrs())) {
					replacements = new Triplet<Symbol, LNode, int>[vars.Count].AsInternalList();
					for (int i = 0; i < vars.Count; i++) {
						replacements.InternalArray[i].A = vars[i].Name;
						
						// Check for duplicate names
						for (int j = 0; j < i; j++)
							if (replacements[i].A == replacements[j].A && replacements[i].A.Name != "_")
								sink.Error(vars[i], "Duplicate name in the left-hand tuple"); // non-fatal
					}
				} else
					return Reject(sink, var, "The left-hand side of 'in' should be a simple identifier or a tuple of simple identifiers.");
			}

			UnrollCtx ctx = new UnrollCtx { Replacements = replacements };
			WList<LNode> output = new WList<LNode>();
			int iteration = 0;
			foreach (LNode replacement in cases)
			{
				iteration++;
				bool tuple = replacement.Calls(S.Tuple) || replacement.Calls(S.Braces);
				int count = tuple ? replacement.ArgCount : 1;
				if (replacements.Count != count)
				{
					sink.Error(replacement, "iteration {0}: Expected {1} replacement items, got {2}", iteration, replacements.Count, count);
					if (count < replacements.Count)
						continue; // too few
				}
				for (int i = 0; i < replacements.Count; i++)
					replacements.InternalArray[i].B = tuple ? replacement.Args[i] : replacement;

				if (body.Calls(S.Braces)) {
					foreach (LNode stmt in body.Args)
						output.Add(ctx.Replace(stmt).Value);
				} else
					output.Add(ctx.Replace(body).Value);
			}

			foreach (var r in replacements)
				if (r.C == 0 && !r.A.Name.StartsWith("_"))
					sink.Write(Severity.Warning, var, "Replacement variable '{0}' was never used", r.A);
			
			return body.With(S.Splice, output.ToVList());
		}
Exemple #27
0
		/// <summary>Gets a new list with any #trivia_trailing attributes removed. Those trivia are returned in an `out` parameter.</summary>
		public static VList<LNode> WithoutTrailingTrivia(this VList<LNode> attrs, out VList<LNode> trailingTrivia)
		{
			var trailingTrivia2 = VList<LNode>.Empty;
			attrs = attrs.Transform((int i, ref LNode attr) => {
				if (attr.Calls(S.TriviaTrailing)) {
					trailingTrivia2.AddRange(attr.Args);
					return XfAction.Drop;
				}
				return XfAction.Keep;
			});
			trailingTrivia = trailingTrivia2; // cannot use `out` parameter within lambda method
			return attrs;
		}
			public AltType(VList<LNode> classAttrs, LNode typeName, VList<LNode> baseTypes, AltType parentType)
			{
				_classAttrs = classAttrs;
				TypeName = typeName;
				BaseTypes = baseTypes;
				ParentType = parentType;
				//matchCode (TypeName) {
				//	case $stem<$(..a)>, $stem: 
				//		_typeNameStem = stem;
				//		_genericArgs = a; 
				//  default:
				//		_genericArgs = new WList<LNode>();
				//}
				{	// Above matchCode expanded:
					LNode stem;
					VList<LNode> a = default(VList<LNode>);
					if (TypeName.CallsMin(CodeSymbols.Of, 1) && (stem = TypeName.Args[0]) != null && (a = new VList<LNode>(TypeName.Args.Slice(1))).IsEmpty | true || (stem = TypeName) != null) {
						_typeNameStem = stem;
						_genericArgs = a.ToWList();
					} else {
						_genericArgs = new WList<LNode>();
					}
				}
				if (ParentType != null) {
					BaseTypes.Insert(0, ParentType.TypeNameWithoutAttrs);
				
					// Search for all 'where' clauses on the ParentType and make sure OUR generic args have them too.
					bool changed = false;
					for (int i = 0; i < _genericArgs.Count; i++) {
						var arg = _genericArgs[i];
						var parentArg = ParentType._genericArgs.FirstOrDefault(a => a.IsIdNamed(arg.Name));
						if (parentArg != null) {
							var wheres = new HashSet<LNode>(WhereTypes(arg));
							int oldCount = wheres.Count;
							var parentWheres = WhereTypes(parentArg);
							foreach (var where in parentWheres)
								wheres.Add(where);
							if (wheres.Count > oldCount) {
								arg = arg.WithAttrs(arg.Attrs.SmartWhere(a => !a.Calls(S.Where))
								.Add(LNode.Call(S.Where, LNode.List(wheres))));
								_genericArgs[i] = arg;
								changed = true;
							}
						}
					}
					if (changed)
						TypeName = LNode.Call(CodeSymbols.Of, LNode.List().Add(_typeNameStem).AddRange(_genericArgs)).SetStyle(NodeStyle.Operator);
				}
				TypeNameWithoutAttrs = TypeName.Select(n => n.WithoutAttrs());
			}
Exemple #29
0
		public static LNode UseSymbolsCore(VList<LNode> symbolAttrs, VList<LNode> options, VList<LNode> body, IMacroContext context, bool inType)
		{
			// Decode options (TODO: invent a simpler approach)
			string prefix = "sy_";
			var inherited = new HashSet<Symbol>();
			foreach (var pair in MacroContext.GetOptions(options))
			{
				if (pair.Key.Name.Name == "prefix" && pair.Value.IsId)
					prefix = pair.Value.Name.Name;
				else if (pair.Key.Name.Name == "inherit" && pair.Value.Value is Symbol)
					inherited.Add((Symbol)pair.Value.Value);
				else if (pair.Key.Name.Name == "inherit" && (pair.Value.Calls(S.Braces) || pair.Value.Calls(S.Tuple)) && pair.Value.Args.All(n => n.Value is Symbol))
					foreach (var arg in pair.Value.Args)
						inherited.Add((Symbol)arg.Value);
				else
					context.Sink.Warning(pair.Value, "Unrecognized parameter. Expected prefix:id or inherit:{@@A; @@B; ...})");
			}

			// Replace all symbols while collecting a list of them
			var symbols = new Dictionary<Symbol, LNode>();
			VList<LNode> output = body.SmartSelect(stmt => stmt.ReplaceRecursive(n => {
				if (!inType && n.ArgCount == 3) {
					// Since we're outside any type, we must avoid creating symbol 
					// fields. When we cross into a type then we can start making
					// Symbols by calling ourself recursively with inType=true
					var kind = EcsValidators.SpaceDefinitionKind(n);
					if (kind == S.Class || kind == S.Struct || kind == S.Interface || kind == S.Alias || kind == S.Trait) {
						var body2 = n.Args[2];
						return n.WithArgChanged(2, UseSymbolsCore(symbolAttrs, options, body2.Args, context, true).WithName(body2.Name));
					}
				}
				var sym = n.Value as Symbol;
				if (n.IsLiteral && sym != null)
					return symbols[sym] = LNode.Id(prefix + sym.Name);
				return null;
			}));

			// Return updated code with variable declaration at the top for all non-inherit symbols used.
			var _Symbol = F.Id("Symbol");
			var vars = (from sym in symbols
			            where !inherited.Contains(sym.Key)
			            select F.Call(S.Assign, sym.Value, 
			                   F.Call(S.Cast, F.Literal(sym.Key.Name), _Symbol))).ToList();
			if (vars.Count > 0)
				output.Insert(0, F.Call(S.Var, ListExt.Single(_Symbol).Concat(vars))
					.WithAttrs(symbolAttrs.Add(F.Id(S.Static)).Add(F.Id(S.Readonly))));
			return F.Call(S.Splice, output);
		}
Exemple #30
0
		public VList<LNode> ExprList(ref TokenType endMarker, VList<LNode> list, bool allowBlockCalls)
		{
			TT la0;
			LNode e = default(LNode);
			Token end = default(Token);
			NewlinesOpt();
			// Line 89: (TopExpr)?
			switch ((TT) LA0) {
			case TT.Assignment: case TT.At: case TT.BQId: case TT.BQOperator:
			case TT.Id: case TT.Keyword: case TT.LBrace: case TT.LBrack:
			case TT.Literal: case TT.LParen: case TT.NegativeLiteral: case TT.NormalOp:
			case TT.Not: case TT.PrefixOp: case TT.PreOrSufOp: case TT.SingleQuoteOp:
				e = TopExpr();
				break;
			}
			// Line 90: ((TT.Comma|TT.Newline|TT.Semicolon) NewlinesOpt ( / TopExpr) ErrorTokensOpt)*
			for (;;) {
				la0 = (TT) LA0;
				if (la0 == TT.Comma || la0 == TT.Newline || la0 == TT.Semicolon) {
					end = MatchAny();
					// line 91
					CheckEndMarker(ref endMarker, ref end);
					NewlinesOpt();
					// line 93
					list.Add(e ?? MissingExpr(end));
					// Line 94: ( / TopExpr)
					switch ((TT) LA0) {
					case EOF: case TT.Comma: case TT.Newline: case TT.RBrace:
					case TT.RBrack: case TT.RParen: case TT.Semicolon:
						// line 94
						e = null;
						break;
					default:
						e = TopExpr();
						break;
					}
					ErrorTokensOpt();
				} else
					break;
			}
			if (e != null || end.Type() == TT.Comma) {
				list.Add(e ?? MissingExpr(end));
			}
			return list;
		}
Exemple #31
0
        /// <summary>
        ///     Returns rows from the DataSource that meet the parameter conditions.
        /// </summary>
        /// <param name="parameters">A collection of <see cref="SqlFilterParameter"/> objects.</param>
        /// <param name="orderBy">Specifies the sort criteria for the rows in the DataSource (Name ASC; BirthDay DESC, Name ASC);</param>
        /// <param name="start">Row number at which to start reading.</param>
        /// <param name="pageLength">Number of rows to return.</param>
        /// <param name="count">out. The number of rows that match this query.</param>
        /// <returns>Returns a typed collection of <c>VJobCandidate</c> objects.</returns>
        public override VList <VJobCandidate> Find(IFilterParameterCollection parameters, string orderBy, int start, int pageLength, out int count)
        {
            // throws security exception if not authorized
            //SecurityContext.IsAuthorized("Find");

            // get this data
            TransactionManager    transactionManager = null;
            VList <VJobCandidate> list = null;

            count = -1;

            try
            {
                //since this is a read operation, don't create a tran by default, only use tran if provided to us for custom isolation level
                transactionManager = ConnectionScope.ValidateOrCreateTransaction(noTranByDefault);
                NetTiersProvider dataProvider = ConnectionScope.Current.DataProvider;

                //Access repository
                list = dataProvider.VJobCandidateProvider.Find(transactionManager, parameters, orderBy, start, pageLength, out count);
            }
            catch (Exception exc)
            {
                //if open, rollback, it's possible this is part of a larger commit
                if (transactionManager != null && transactionManager.IsOpen)
                {
                    transactionManager.Rollback();
                }

                //Handle exception based on policy
                if (DomainUtil.HandleException(exc, layerExceptionPolicy))
                {
                    throw;
                }
            }

            return(list);
        }
Exemple #32
0
            protected override void WriteOutput(InputOutput io)
            {
                VList <LNode> results = io.Output;
                string        NewlineString = io.OutOptions.NewlineString, IndentString = io.OutOptions.IndentString;

                if (!NoOutHeader)
                {
                    Output.AppendFormat(
                        "// Generated from {1} by LeMP custom tool. LeMP version: {2}{0}"
                        + "// Note: you can give command-line arguments to the tool via 'Custom Tool Namespace':{0}"
                        + "// --no-out-header       Suppress this message{0}"
                        + "// --verbose             Allow verbose messages (shown by VS as 'warnings'){0}"
                        + "// --timeout=X           Abort processing thread after X seconds (default: 10){0}"
                        + "// --macros=FileName.dll Load macros from FileName.dll, path relative to this file {0}"
                        + "// Use #importMacros to use macros in a given namespace, e.g. #importMacros(Loyc.LLPG);{0}", NewlineString,
                        Path.GetFileName(io.FileName), typeof(MacroProcessor).Assembly.GetName().Version.ToString());
                }
                var options = new LNodePrinterOptions {
                    IndentString = IndentString, NewlineString = NewlineString
                };

                using (LNode.SetPrinter(io.OutPrinter ?? LNode.Printer))
                    LNode.Printer.Print(results, Output, Sink, ParsingMode.File, options);
            }
Exemple #33
0
        public VList <LNode> ProcessFile(InputOutput io, Action <InputOutput> onProcessed)
        {
            using (ParsingService.PushCurrent(io.InputLang ?? ParsingService.Current)) {
                try {
                    string dir = Path.GetDirectoryName(io.FileName);
                    if (!string.IsNullOrEmpty(dir))
                    {
                        _rootScopedProperties[(Symbol)"#inputFolder"] = dir;
                    }
                    _rootScopedProperties[(Symbol)"#inputFileName"] = Path.GetFileName(io.FileName);
                } catch (ArgumentException) { }                    // Path.* may throw
                catch (PathTooLongException) { }                   // Path.* may throw

                var input   = ParsingService.Current.Parse(io.Text, io.FileName, _sink);
                var inputRV = new VList <LNode>(input);

                io.Output = ProcessRoot(inputRV);
                if (onProcessed != null)
                {
                    onProcessed(io);
                }
                return(io.Output);
            }
        }
Exemple #34
0
        /// <summary>
        /// Get a set portion of a complete list of <see cref="VProductModelInstructions" /> entities
        /// </summary>
        /// <param name="start">Row number at which to start reading.</param>
        /// <param name="pageLength">Number of rows to return.</param>
        /// <param name="totalCount">out parameter, number of total rows in given query.</param>
        /// <returns>a <see cref="TList{VProductModelInstructions}"/> </returns>
        public override VList <VProductModelInstructions> GetAll(int start, int pageLength, out int totalCount)
        {
            // throws security exception if not authorized
            //SecurityContext.IsAuthorized("GetAll");

            // get this data
            VList <VProductModelInstructions> list = null;

            totalCount = -1;
            TransactionManager transactionManager = null;

            try
            {
                //since this is a read operation, don't create a tran by default, only use tran if provided to us for custom isolation level
                transactionManager = ConnectionScope.ValidateOrCreateTransaction(noTranByDefault);
                NetTiersProvider dataProvider = ConnectionScope.Current.DataProvider;

                //Access repository
                list = dataProvider.VProductModelInstructionsProvider.GetAll(transactionManager, start, pageLength, out totalCount);
            }
            catch (Exception exc)
            {
                //if open, rollback, it's possible this is part of a larger commit
                if (transactionManager != null && transactionManager.IsOpen)
                {
                    transactionManager.Rollback();
                }

                //Handle exception based on policy
                if (DomainUtil.HandleException(exc, layerExceptionPolicy))
                {
                    throw;
                }
            }
            return(list);
        }
Exemple #35
0
        public void BuildRouted()
        {
            VList.SDModelSetup  += OnSDModelSetup;
            VList.SDModelClose  += OnSDModelClose;
            VList.SDModelLock   += OnSDModelLock;
            VList.SDModelView   += OnSDModelView;
            VList.SDModelUnlock += OnSDModelUnlock;
            VList.SDModelUnview += OnSDModelUnview;
            VList.BuildRouted(this);

            VChart.SDModelRun     += OnSDModelRun;
            VChart.SDModelCopy    += OnSDModelCopy;
            VChart.SDModelCut     += OnSDModelCut;
            VChart.SDModelPaste   += OnSDModelPaste;
            VChart.SDModelSelect  += OnSDModelSelect;
            VChart.SDModelDelete  += OnSDModelDelete;
            VChart.SDModelDraw    += OnSDModelDraw;
            VChart.XYModelCreate  += OnXYModelCreate;
            VChart.SDModelSave    += OnSDModelSave;
            VChart.SDModelLoad    += OnSDModelLoad;
            VChart.SDModelSaveAll += OnSDModelSaveAll;
            VChart.SDModelLoadAll += OnSDModelLoadAll;
            VChart.BuildRouted(this);
        }
Exemple #36
0
        LNode KeywordExpression()
        {
            TT    la0, la1;
            Token kw     = default(Token);
            LNode result = default(LNode);
            // line 291
            var args = new VList <LNode>();

            kw = MatchAny();
            // line 293
            var keyword = kw.Value as Symbol;

            // Line 295: ((EOF|TT.Newline|TT.RBrace|TT.RBrack|TT.RParen|TT.Semicolon) =>  / Expr)
            switch ((TT)LA0)
            {
            case EOF:
            case TT.Newline:
            case TT.RBrace:
            case TT.RBrack:
            case TT.RParen:
            case TT.Semicolon:
            { }
            break;

            default:
                args.Add(Expr(Precedence.MinValue));
                break;
            }
            // Line 297: greedy((TT.Newline)? BracedBlock)?
            do
            {
                la0 = (TT)LA0;
                if (la0 == TT.Newline)
                {
                    la1 = (TT)LA(1);
                    if (la1 == TT.LBrace)
                    {
                        goto matchBracedBlock;
                    }
                }
                else if (la0 == TT.LBrace)
                {
                    goto matchBracedBlock;
                }
                break;
matchBracedBlock:
                {
                    // Line 297: (TT.Newline)?
                    la0 = (TT)LA0;
                    if (la0 == TT.Newline)
                    {
                        Skip();
                    }
                    args.Add(BracedBlock());
                }
            } while (false);
            // Line 298: greedy(Continuator)*
            for (;;)
            {
                la0 = (TT)LA0;
                if (la0 == TT.Newline)
                {
                    la1 = (TT)LA(1);
                    if (la1 == TT.Id)
                    {
                        if (IsContinuator(LT(1).Value))
                        {
                            args.Add(Continuator());
                        }
                        else
                        {
                            break;
                        }
                    }
                    else
                    {
                        break;
                    }
                }
                else if (la0 == TT.Id)
                {
                    if (IsContinuator(LT(0).Value))
                    {
                        args.Add(Continuator());
                    }
                    else
                    {
                        break;
                    }
                }
                else
                {
                    break;
                }
            }
            // line 300
            int endIndex = args.IsEmpty ? kw.EndIndex : args.Last.Range.EndIndex;

            result = MarkSpecial(F.Call(keyword, args, kw.StartIndex, endIndex, kw.StartIndex, kw.EndIndex));
            return(result);
        }
Exemple #37
0
        public VList <LNode> ExprList(ref TokenType endMarker, VList <LNode> list = default(VList <LNode>), bool isBracedBlock = false)
        {
            TT            la0;
            LNode         e      = default(LNode);
            Token         end    = default(Token);
            VList <LNode> result = default(VList <LNode>);

            NewlinesOpt();
            // Line 82: (TopExpr)?
            switch ((TT)LA0)
            {
            case TT.Assignment:
            case TT.At:
            case TT.BQId:
            case TT.BQOperator:
            case TT.Id:
            case TT.Keyword:
            case TT.LBrace:
            case TT.LBrack:
            case TT.Literal:
            case TT.LParen:
            case TT.NormalOp:
            case TT.Not:
            case TT.PrefixOp:
            case TT.PreOrSufOp:
            case TT.SingleQuoteOp:
                e = TopExpr();
                break;
            }
            // Line 83: ((&{isBracedBlock} (TT.RBrack|TT.RParen))? (TT.Comma|TT.Newline|TT.Semicolon) NewlinesOpt ({..} / TopExpr) ErrorTokensOpt)*
            for (;;)
            {
                switch ((TT)LA0)
                {
                case TT.RBrack:
                case TT.RParen:
                {
                    if (isBracedBlock)
                    {
                        goto match1;
                    }
                    else
                    {
                        goto stop;
                    }
                }

                case TT.Comma:
                case TT.Newline:
                case TT.Semicolon:
                    goto match1;

                default:
                    goto stop;
                }
match1:
                {
                    // Line 83: (&{isBracedBlock} (TT.RBrack|TT.RParen))?
                    la0 = (TT)LA0;
                    if (la0 == TT.RBrack || la0 == TT.RParen)
                    {
                        Check(isBracedBlock, "Expected isBracedBlock");
                        // line 83
                        Error(0, "Unexpected closing bracket");
                        Skip();
                    }
                    end = Match((int)TT.Comma, (int)TT.Newline, (int)TT.Semicolon);
                    // line 85
                    CheckEndMarker(ref endMarker, ref end);
                    NewlinesOpt();
                    // line 87
                    list.Add(e ?? MissingExpr(end));
                    // Line 88: ({..} / TopExpr)
                    switch ((TT)LA0)
                    {
                    case EOF:
                    case TT.Comma:
                    case TT.Newline:
                    case TT.RBrace:
                    case TT.RBrack:
                    case TT.RParen:
                    case TT.Semicolon:
                        // line 88
                        e = null;
                        break;

                    default:
                        e = TopExpr();
                        break;
                    }
                    ErrorTokensOpt();
                }
            }
            stop :;
            // line 91
            if (e != null || end.Type() == TT.Comma)
            {
                list.Add(e ?? MissingExpr(end, afterToken : true));
            }
            result = list;
            return(result);
        }
Exemple #38
0
            public AltType(VList <LNode> classAttrs, LNode typeName, VList <LNode> baseTypes, AltType parentType)
            {
                _classAttrs = classAttrs;
                TypeName    = typeName;
                BaseTypes   = baseTypes;
                ParentType  = parentType;
                //matchCode (TypeName) {
                //	case $stem<$(..a)>, $stem:
                //		_typeNameStem = stem;
                //		_genericArgs = a;
                //  default:
                //		_genericArgs = new WList<LNode>();
                //}
                {                       // Above matchCode expanded:
                    LNode         stem;
                    VList <LNode> a = default(VList <LNode>);
                    if (TypeName.CallsMin(CodeSymbols.Of, 1) && (stem = TypeName.Args[0]) != null && (a = new VList <LNode>(TypeName.Args.Slice(1))).IsEmpty | true || (stem = TypeName) != null)
                    {
                        _typeNameStem = stem;
                        _genericArgs  = a.ToWList();
                    }
                    else
                    {
                        _genericArgs = new WList <LNode>();
                    }
                }
                if (ParentType != null)
                {
                    BaseTypes.Insert(0, ParentType.TypeNameWithoutAttrs);

                    // Search for all 'where' clauses on the ParentType and make sure OUR generic args have them too.
                    bool changed = false;
                    for (int i = 0; i < _genericArgs.Count; i++)
                    {
                        var arg       = _genericArgs[i];
                        var parentArg = ParentType._genericArgs.FirstOrDefault(a => a.IsIdNamed(arg.Name));
                        if (parentArg != null)
                        {
                            var wheres       = new HashSet <LNode>(WhereTypes(arg));
                            int oldCount     = wheres.Count;
                            var parentWheres = WhereTypes(parentArg);
                            foreach (var where in parentWheres)
                            {
                                wheres.Add(where);
                            }
                            if (wheres.Count > oldCount)
                            {
                                arg = arg.WithAttrs(arg.Attrs.SmartWhere(a => !a.Calls(S.Where))
                                                    .Add(LNode.Call(S.Where, LNode.List(wheres))));
                                _genericArgs[i] = arg;
                                changed         = true;
                            }
                        }
                    }
                    if (changed)
                    {
                        TypeName = LNode.Call(CodeSymbols.Of, LNode.List().Add(_typeNameStem).AddRange(_genericArgs)).SetStyle(NodeStyle.Operator);
                    }
                }
                TypeNameWithoutAttrs = TypeName.Select(n => n.WithoutAttrs());
            }
 public AltType(VList <LNode> classAttrs, LNode typeName, VList <LNode> baseTypes, AltType parentType)
 {
     _classAttrs = classAttrs;
     TypeName    = typeName;
     BaseTypes   = baseTypes;
     ParentType  = parentType;
     {
         LNode         stem;
         VList <LNode> a = default(VList <LNode>);
         if (TypeName.CallsMin(CodeSymbols.Of, 1) && (stem = TypeName.Args[0]) != null && (a = new VList <LNode>(TypeName.Args.Slice(1))).IsEmpty | true || (stem = TypeName) != null)
         {
             _typeNameStem = stem;
             _genericArgs  = a.ToWList();
         }
         else
         {
             _genericArgs = new WList <LNode>();
         }
     }
     if (ParentType != null)
     {
         BaseTypes.Insert(0, ParentType.TypeNameWithoutAttrs);
         bool changed = false;
         for (int i = 0; i < _genericArgs.Count; i++)
         {
             var arg       = _genericArgs[i];
             var parentArg = ParentType._genericArgs.FirstOrDefault(a => a.IsIdNamed(arg.Name));
             if (parentArg != null)
             {
                 var wheres       = new HashSet <LNode>(WhereTypes(arg));
                 int oldCount     = wheres.Count;
                 var parentWheres = WhereTypes(parentArg);
                 foreach (var where in parentWheres)
                 {
                     wheres.Add(where);
                 }
                 if (wheres.Count > oldCount)
                 {
                     arg             = arg.WithAttrs(arg.Attrs.Where(a => !a.Calls(S.Where)).Add(LNode.Call(S.Where, LNode.List(wheres))));
                     _genericArgs[i] = arg;
                     changed         = true;
                 }
             }
         }
         if (changed)
         {
             TypeName = LNode.Call(CodeSymbols.Of, LNode.List().Add(_typeNameStem).AddRange(_genericArgs));
         }
     }
     TypeNameWithoutAttrs = TypeName.Select(n => n.WithoutAttrs());
 }
Exemple #40
0
            void ProcessEnsuresAttribute(VList <LNode> conditions, Symbol mode, LNode exceptionType, LNode variableName)
            {
                // Create a "Contract.Whatever()" check for each provided condition.
                bool haveCCRewriter = _haveCCRewriter && mode != sy_ensuresAssert && mode != sy_ensuresFinally;
                var  checks         = LNode.List();

                foreach (var condition_ in conditions)
                {
                    LNode condition = condition_;                       // make it writable so we can replace `_`
                    LNode conditionStr;

                    LNode  contractResult  = null;
                    string underscoreError = null;
                    if (mode == sy_ensuresOnThrow)
                    {
                        contractResult = Id__exception__;
                        if (haveCCRewriter)
                        {
                            underscoreError = "`ensuresOnThrow` does not support `_` in MS Code Contracts mode.";
                        }
                    }
                    else                                // @@ensures or @@ensuresAssert or @@ensuresFinally
                    {
                        contractResult = haveCCRewriter ? LNode.Call(LNode.Call(CodeSymbols.Dot, LNode.List(LNode.Id((Symbol)"Contract"), LNode.Call(CodeSymbols.Of, LNode.List(LNode.Id((Symbol)"Result"), ReturnType)).SetStyle(NodeStyle.Operator))).SetStyle(NodeStyle.Operator)) : Id_return_value;
                        if (mode == sy_ensuresFinally)
                        {
                            underscoreError = "The macro for `{0}` does not support `_` because the return value is not available in `finally`";
                        }
                        else if (haveCCRewriter && ReturnType.IsIdNamed(S.Missing))
                        {
                            underscoreError = "The macro for `{0}` does not support `_` in this context when MS Code Contracts are enabled, because the return type is unknown.";
                        }
                        bool changed = ReplaceContractUnderscore(ref condition, contractResult);
                    }
                    if (ReplaceContractUnderscore(ref condition, contractResult) && underscoreError != null)
                    {
                        Context.Sink.Error(condition, underscoreError, mode);
                    }

                    if (haveCCRewriter)
                    {
                        if (mode == sy_ensuresOnThrow)
                        {
                            checks.Add(exceptionType != null
                                                        ? LNode.Call(LNode.Call(CodeSymbols.Dot, LNode.List(LNode.Id((Symbol)"Contract"), LNode.Call(CodeSymbols.Of, LNode.List(LNode.Id((Symbol)"EnsuresOnThrow"), exceptionType)).SetStyle(NodeStyle.Operator))).SetStyle(NodeStyle.Operator), LNode.List(condition)) : LNode.Call(LNode.Call(CodeSymbols.Dot, LNode.List(LNode.Id((Symbol)"Contract"), LNode.Id((Symbol)"EnsuresOnThrow"))).SetStyle(NodeStyle.Operator), LNode.List(condition)));
                        }
                        else
                        {
                            checks.Add(LNode.Call(LNode.Call(CodeSymbols.Dot, LNode.List(LNode.Id((Symbol)"Contract"), LNode.Id((Symbol)"Ensures"))).SetStyle(NodeStyle.Operator), LNode.List(condition)));
                        }
                    }
                    else
                    {
                        conditionStr = ConditionToStringLit(condition,
                                                            mode == sy_ensuresOnThrow
                                                ? "Postcondition failed after throwing an exception: {1}" :
                                                            "Postcondition failed: {1}");


                        if (mode == sy_ensuresOnThrow)
                        {
                            var excType = GetExceptionTypeForEnsuresOnThrow();
                            checks.Add(LNode.Call(CodeSymbols.If, LNode.List(LNode.Call(CodeSymbols.Not, LNode.List(condition)).SetStyle(NodeStyle.Operator), LNode.Call(CodeSymbols.Throw, LNode.List(LNode.Call(CodeSymbols.New, LNode.List(LNode.Call(excType, LNode.List(conditionStr, Id__exception__)))))))));
                        }
                        else
                        {
                            LNode assertMethod;
                            if (mode == sy_ensuresAssert)
                            {
                                assertMethod = GetAssertMethod(Context);
                            }
                            else if (mode == sy_ensuresFinally)
                            {
                                assertMethod = GetAssertMethodForEnsuresFinally();
                            }
                            else
                            {
                                assertMethod = GetAssertMethodForEnsures();
                            }

                            checks.Add(LNode.Call(assertMethod, LNode.List(condition, conditionStr)));
                        }
                    }
                }

                // Request that the checks be added to the beginning of the method
                if (checks.Count > 0)
                {
                    if (_haveCCRewriter)
                    {
                        PrependStmts.AddRange(checks);
                    }
                    else if (mode == sy_ensuresOnThrow)
                    {
                        LNode excSpec = exceptionType == null ? Id__exception__ : LNode.Call(CodeSymbols.Var, LNode.List(exceptionType, Id__exception__));
                        PrependStmts.Add(LNode.Call((Symbol)"on_throw", LNode.List(excSpec, LNode.Call(CodeSymbols.Braces, LNode.List(checks)).SetStyle(NodeStyle.Statement))).SetStyle(NodeStyle.Special));
                    }
                    else if (mode == sy_ensuresFinally)
                    {
                        PrependStmts.Add(LNode.Call((Symbol)"on_finally", LNode.List(LNode.Call(CodeSymbols.Braces, LNode.List(checks)).SetStyle(NodeStyle.Statement))).SetStyle(NodeStyle.Special));
                    }
                    else                                // mode == @@ensures || mode == @@ensuresAssert
                    {
                        PrependStmts.Add(LNode.Call((Symbol)"on_return", LNode.List(Id_return_value, LNode.Call(CodeSymbols.Braces, LNode.List(checks)).SetStyle(NodeStyle.Statement))).SetStyle(NodeStyle.Special));
                    }
                }
            }
Exemple #41
0
        static bool CaptureGroup(ref int c, ref int p, VList <LNode> cArgs, VList <LNode> pArgs, ref MMap <Symbol, LNode> captures, ref VList <LNode> attrs)
        {
            Debug.Assert(IsParamsCapture(pArgs[p]));
            // The goal now is to find a sequence of nodes in cArgs that matches
            // the sequence pArgs[p+1 .. p+x] where x is the maximum value such
            // that none of the nodes in the sequence are $(params caps).
            int saved_p = p, saved_c = c;
            var savedCaptures = captures.AsImmutable();
            var savedAttrs    = attrs;
            int captureSize   = 0;

            for (;; captureSize++)
            {
                for (p++, c += captureSize; ; c++, p++)
                {
                    // If we run out of pArgs, great, we're done; if we run out
                    // of cArgs, the match fails, unless all remaining pArgs are
                    // $(params caps).
                    if (p >= pArgs.Count || IsParamsCapture(pArgs[p]))
                    {
                        goto done_group;
                    }
                    else
                    {
                        if (c >= cArgs.Count)
                        {
                            return(false);
                        }
                        if (!MatchesPatternNested(cArgs[c], pArgs[p], ref captures, ref attrs))
                        {
                            goto continue_group;
                        }
                    }
                }
                continue_group :;
                p        = saved_p;
                c        = saved_c;
                attrs    = savedAttrs;
                captures = savedCaptures.AsMutable();
            }
done_group:
            AddCapture(captures, pArgs[saved_p], cArgs.Slice(saved_c, captureSize));
            return(true);
        }
Exemple #42
0
        static bool MatchThenParams(VList <LNode> cArgs, VList <LNode> pArgs, LNode paramsCap, ref MMap <Symbol, LNode> captures, ref VList <LNode> attrs)
        {
            // This helper function of MatchesPattern() is called when pArgs is followed
            // by a $(params capture). cArgs is the list of candidate.Args that have not
            // yet been matched; pArgs is the list of pattern.Args that have not yet been
            // matched, and paramsCap is the $(params capture) node that follows pArgs.
            captures = captures ?? new MMap <Symbol, LNode>();
            int c = 0, p = 0;

restart:
            for (; p < pArgs.Count; p++, c++)
            {
                if (IsParamsCapture(pArgs[p]))
                {
                    if (!CaptureGroup(ref c, ref p, cArgs, pArgs, ref captures, ref attrs))
                    {
                        return(false);
                    }
                    goto restart;
                }
                else
                {
                    if (c >= cArgs.Count)
                    {
                        return(false);
                    }
                    if (!MatchesPatternNested(cArgs[c], pArgs[p], ref captures, ref attrs))
                    {
                        return(false);
                    }
                }
            }
            AddCapture(captures, paramsCap, new Slice_ <LNode>(cArgs, c));
            return(true);
        }
Exemple #43
0
 static bool AttributesMatch(LNode candidate, LNode pattern, ref MMap <Symbol, LNode> captures, out VList <LNode> unmatchedAttrs)
 {
     if (pattern.HasPAttrs())
     {
         throw new NotImplementedException("TODO: attributes in patterns are not yet supported");
     }
     unmatchedAttrs = candidate.Attrs;
     return(true);
 }
Exemple #44
0
 public LNode Call(string target, VList <LNode> args, int startIndex = -1, int endIndex = -1)
 {
     return(Call(GSymbol.Get(target), args, startIndex, endIndex));
 }
Exemple #45
0
        public static LNode match(LNode node, IMacroContext context)
        {
            {
                LNode         input;
                VList <LNode> contents;
                if (node.Args.Count == 2 && (input = node.Args[0]) != null && node.Args[1].Calls(CodeSymbols.Braces))
                {
                    contents = node.Args[1].Args;
                    var outputs = new WList <LNode>();
                    input = MaybeAddTempVarDecl(context, input, outputs);

                    // Process the braced block, one case at a time
                    int next_i = 0;
                    for (int case_i = 0; case_i < contents.Count; case_i = next_i)
                    {
                        var @case = contents[case_i];
                        if (!IsCaseLabel(@case)                         // `case ...:` or `default:`
                            )
                        {
                            return(Reject(context, contents[0], "In 'match': expected 'case' statement"));
                        }
                        // Find the end of the current case/default block
                        for (next_i = case_i + 1; next_i < contents.Count; next_i++)
                        {
                            var stmt = contents[next_i];
                            if (IsCaseLabel(stmt))
                            {
                                break;
                            }
                            if (stmt.Calls(S.Break, 0))
                            {
                                next_i++;
                                break;
                            }
                        }
                        //  handler: the list of statements underneath `case`
                        var handler = new VList <LNode>(contents.Slice(case_i + 1, next_i - (case_i + 1)));

                        if (@case.Calls(S.Case) && @case.Args.Count > 0)
                        {
                            var codeGen = new CodeGeneratorForMatchCase(context, input, handler);
                            foreach (var pattern in @case.Args)
                            {
                                outputs.Add(codeGen.GenCodeForPattern(pattern));
                            }
                        }
                        else                                    // default:
                        // Note: the extra {braces} around the handler are rarely
                        // needed. They are added just in case the handler declares a
                        // variable and a different handler declares another variable
                        // by the same name, which is illegal unless we add braces.
                        {
                            outputs.Add(LNode.Call(CodeSymbols.Braces, LNode.List(handler)).SetStyle(NodeStyle.Statement));
                            if (next_i < contents.Count)
                            {
                                context.Sink.Error(contents[next_i], "The default branch must be the final branch in a 'match' statement.");
                            }
                        }
                    }
                    return(LNode.Call(CodeSymbols.DoWhile, LNode.List(outputs.ToVList().AsLNode(S.Braces), LNode.Literal(false))));
                }
            }
            return(null);
        }
Exemple #46
0
        public static VList <LNode> WithoutNodeNamed(this VList <LNode> a, Symbol name)
        {
            LNode _;

            return(WithoutNodeNamed(a, name, out _));
        }
Exemple #47
0
        public static LNode ContractsOnProperty(LNode prop, IMacroContext context)
        {
            // Performance note: one should keep in mind that this macro usually
            // has no effect. It looks for contracts and usually finds none.
            LNode oldProp = prop;

            if (prop.ArgCount == 4)
            {
                LNode braces    = prop[3];
                var   oldBraces = braces;
                var   rw        = new CodeContractRewriter(prop.Args[0], prop.Args[1], context);

                // If this has an argument list (this[...]), process its contract attributes
                prop = ProcessArgContractAttributes(prop, 2, rw);

                // Remove contract attributes from the property and store in a list
                VList <LNode> cAttrs = LNode.List();
                prop = prop.WithArgChanged(0, GrabContractAttrs(prop.Args[0], ref cAttrs, ContractAppliesTo.Getter));
                prop = GrabContractAttrs(prop, ref cAttrs);

                // Find the getter and setter
                LNode         getter = null, setter = null;
                int           getterIndex = -1, setterIndex = -1;
                VList <LNode> getterAttrs = LNode.List(), setterAttrs = LNode.List();
                bool          isLambdaProperty = !braces.Calls(S.Braces);
                if (isLambdaProperty)
                {
                    if (cAttrs.Count == 0)
                    {
                        return(null);                           // lambda property has no contract attributes
                    }
                    // Transform into a normal property
                    getterAttrs = cAttrs;
                    getter      = LNode.Call(CodeSymbols.get, LNode.List(LNode.Call(CodeSymbols.Braces, LNode.List(LNode.Call(CodeSymbols.Return, LNode.List(braces)))).SetStyle(NodeStyle.Statement))).SetStyle(NodeStyle.Special);
                    braces      = LNode.Call(CodeSymbols.Braces, LNode.List(getter)).SetStyle(NodeStyle.Statement);
                    getterIndex = 0;
                }
                else
                {
                    for (int i = 0; i < braces.Args.Count; i++)
                    {
                        var part = braces.Args[i];
                        if (part.Calls(S.get))
                        {
                            getter = part; getterIndex = i;
                        }
                        if (part.Calls(S.set))
                        {
                            setter = part; setterIndex = i;
                        }
                    }

                    // Now create separate lists of contract attributes for the getter and the setter
                    if (cAttrs.Count != 0)
                    {
                        getterAttrs = cAttrs.SmartWhere(a => (PropertyContractInterpretation(a) & ContractAppliesTo.Getter) != 0);
                        setterAttrs = cAttrs.SmartWhere(a => (PropertyContractInterpretation(a) & ContractAppliesTo.Setter) != 0);
                    }
                }

                // Process the discovered attributes to produce prepended statements
                var sharedPrependStmts = rw.PrependStmts;
                if (getter != null)
                {
                    getter = GrabContractAttrs(getter, ref getterAttrs);
                    rw.Process(getterAttrs, null);
                    rw.PrependStmtsToGetterOrSetter(ref braces, getterIndex, getter);
                }
                if (setter != null)
                {
                    rw.PrependStmts = sharedPrependStmts;
                    setter          = GrabContractAttrs(setter, ref setterAttrs);
                    rw.Process(setterAttrs, LNode.Id(CodeSymbols.value), true);
                    rw.PrependStmtsToGetterOrSetter(ref braces, setterIndex, setter);
                }

                // Update the property
                if (braces == oldBraces)
                {
                    return(null);                       // this is the common case
                }
                else
                {
                    return(prop.WithArgChanged(3, braces));
                }
            }
            return(null);
        }
Exemple #48
0
        protected LNode TopExpr()
        {
            TT    la0;
            LNode e         = default(LNode);
            Token lit_colon = default(Token);
            LNode result    = default(LNode);
            // line 120
            int startIndex = LT0.StartIndex;
            // line 121
            var attrs = new VList <LNode>();

            // Line 123: (TT.At (TT.At | Particle) greedy(~(EOF|TT.LBrace|TT.Newline) => {..})? NewlinesOpt)*
            for (;;)
            {
                la0 = (TT)LA0;
                if (la0 == TT.At)
                {
                    Skip();
                    // Line 123: (TT.At | Particle)
                    la0 = (TT)LA0;
                    if (la0 == TT.At)
                    {
                        Skip();
                    }
                    else
                    {
                        attrs.Add(Particle(isAttribute: true));
                    }
                    // Line 124: greedy(~(EOF|TT.LBrace|TT.Newline) => {..})?
                    la0 = (TT)LA0;
                    if (!(la0 == (TT)EOF || la0 == TT.LBrace || la0 == TT.Newline))
                    {
                        // line 124
                        CheckForSpaceAtEndOfAttribute();
                    }
                    NewlinesOpt();
                }
                else
                {
                    break;
                }
            }
            // Line 127: (Expr greedy(TT.Colon (EOF|TT.Newline|TT.RBrace|TT.RBrack|TT.RParen) => )?)
            switch ((TT)LA0)
            {
            case TT.Assignment:
            case TT.BQId:
            case TT.BQOperator:
            case TT.Id:
            case TT.Keyword:
            case TT.LBrace:
            case TT.LBrack:
            case TT.Literal:
            case TT.LParen:
            case TT.NormalOp:
            case TT.Not:
            case TT.PrefixOp:
            case TT.PreOrSufOp:
            case TT.SingleQuoteOp:
            {
                e = Expr(Precedence.MinValue);
                // Line 129: greedy(TT.Colon (EOF|TT.Newline|TT.RBrace|TT.RBrack|TT.RParen) => )?
                la0 = (TT)LA0;
                if (la0 == TT.Colon)
                {
                    lit_colon = MatchAny();
                    // line 130
                    e = F.Call(sy__apos_colonsuf, e, e.Range.StartIndex, lit_colon.EndIndex, lit_colon.StartIndex, lit_colon.EndIndex);
                }
            }
            break;

            default:
            {
                // line 132
                Error(0, "Expected an expression here");
                MatchExcept();
                // Line 133: nongreedy(~(EOF))*
                for (;;)
                {
                    switch ((TT)LA0)
                    {
                    case EOF:
                    case TT.Assignment:
                    case TT.At:
                    case TT.BQId:
                    case TT.BQOperator:
                    case TT.Comma:
                    case TT.Id:
                    case TT.Keyword:
                    case TT.LBrace:
                    case TT.LBrack:
                    case TT.Literal:
                    case TT.LParen:
                    case TT.Newline:
                    case TT.NormalOp:
                    case TT.Not:
                    case TT.PrefixOp:
                    case TT.PreOrSufOp:
                    case TT.RBrace:
                    case TT.RBrack:
                    case TT.RParen:
                    case TT.Semicolon:
                    case TT.SingleQuoteOp:
                        goto stop;

                    default:
                        Skip();
                        break;
                    }
                }
                stop :;
                // Line 134: (TopExpr | (EOF|TT.Comma|TT.Newline|TT.RBrace|TT.RBrack|TT.RParen|TT.Semicolon) => {..})
                switch ((TT)LA0)
                {
                case TT.Assignment : case TT.At : case TT.BQId : case TT.BQOperator :
                case TT.Id         : case TT.Keyword : case TT.LBrace : case TT.LBrack :
                case TT.Literal    : case TT.LParen : case TT.NormalOp : case TT.Not :
                case TT.PrefixOp   : case TT.PreOrSufOp : case TT.SingleQuoteOp :
                    e = TopExpr();
                    break;

                default:
                    // line 134
                    e = MissingExpr(LT0);
                    break;
                }
            }
            break;
            }
            // line 136
            if (!attrs.IsEmpty)
            {
                e = e.PlusAttrsBefore(attrs).WithRange(startIndex, e.Range.EndIndex);
            }
            // line 137
            result = e;
            return(result);
        }
Exemple #49
0
        LNode Expr(Precedence context)
        {
            TT    la0;
            LNode e        = default(LNode);
            Token lit_excl = default(Token);
            Token t        = default(Token);

            // Line 153: (KeywordExpression | PrefixExpr greedy( &{context.CanParse(P.Primary)} FinishPrimaryExpr | &{CanParse(context, $LI, out prec)} InfixOperatorName Expr | &{context.CanParse(_prec.Find(OperatorShape.Suffix, LT($LI).Value))} TT.PreOrSufOp | &{context.CanParse(P.Of)} TT.Not (TT.LParen ExprList TT.RParen / Expr) )*)
            la0 = (TT)LA0;
            if (la0 == TT.Keyword)
            {
                e = KeywordExpression();
            }
            else
            {
                // line 154
                Precedence prec;
                e = PrefixExpr(context);
                // Line 158: greedy( &{context.CanParse(P.Primary)} FinishPrimaryExpr | &{CanParse(context, $LI, out prec)} InfixOperatorName Expr | &{context.CanParse(_prec.Find(OperatorShape.Suffix, LT($LI).Value))} TT.PreOrSufOp | &{context.CanParse(P.Of)} TT.Not (TT.LParen ExprList TT.RParen / Expr) )*
                for (;;)
                {
                    switch ((TT)LA0)
                    {
                    case TT.LBrack:
                    case TT.LParen:
                    {
                        if (context.CanParse(P.Primary))
                        {
                            e = FinishPrimaryExpr(e);
                        }
                        else
                        {
                            goto stop;
                        }
                    }
                    break;

                    case TT.Assignment:
                    case TT.Dot:
                    case TT.NormalOp:
                    {
                        if (CanParse(context, 0, out prec))
                        {
                            goto match2;
                        }
                        else
                        {
                            goto stop;
                        }
                    }

                    case TT.Colon:
                    {
                        if ((TT)LA(0 + 1) != TT.Newline)
                        {
                            if (CanParse(context, 0, out prec))
                            {
                                goto match2;
                            }
                            else
                            {
                                goto stop;
                            }
                        }
                        else
                        {
                            goto stop;
                        }
                    }

                    case TT.Id:
                    {
                        if (!IsContinuator(LT(0).Value))
                        {
                            if (CanParse(context, 0, out prec))
                            {
                                goto match2;
                            }
                            else
                            {
                                goto stop;
                            }
                        }
                        else
                        {
                            goto stop;
                        }
                    }

                    case TT.PreOrSufOp:
                    {
                        if (context.CanParse(_prec.Find(OperatorShape.Suffix, LT(0).Value)))
                        {
                            t = MatchAny();
                            // line 168
                            e = F.Call(_prec.ToSuffixOpName((Symbol)t.Value), e, e.Range.StartIndex, t.EndIndex, t.StartIndex, t.EndIndex, NodeStyle.Operator);
                        }
                        else
                        {
                            goto stop;
                        }
                    }
                    break;

                    case TT.Not:
                    {
                        if (context.CanParse(P.Of))
                        {
                            lit_excl = MatchAny();
                            // line 172
                            var args = new VList <LNode> {
                                e
                            };
                            int endIndex;
                            // Line 173: (TT.LParen ExprList TT.RParen / Expr)
                            la0 = (TT)LA0;
                            if (la0 == TT.LParen)
                            {
                                Skip();
                                args = ExprList(args);
                                var c = Match((int)TT.RParen);
                                // line 173
                                endIndex = c.EndIndex;
                            }
                            else
                            {
                                var T = Expr(P.Of);
                                // line 174
                                args.Add(T);
                                endIndex = T.Range.EndIndex;
                            }
                            // line 176
                            e = F.Call(S.Of, args, e.Range.StartIndex, endIndex, lit_excl.StartIndex, lit_excl.EndIndex, NodeStyle.Operator);
                        }
                        else
                        {
                            goto stop;
                        }
                    }
                    break;

                    default:
                        goto stop;
                    }
                    continue;
match2:
                    {
                        Token op;
                        var   opName = InfixOperatorName(out op);
                        var   rhs    = Expr(prec);
                        // line 164
                        e = F.Call(opName, e, rhs, e.Range.StartIndex, rhs.Range.EndIndex, op.StartIndex, op.EndIndex, NodeStyle.Operator);
                    }
                }
                stop :;
            }
            // line 178
            return(e);
        }
Exemple #50
0
        public VList <LNode> ExprList(VList <LNode> list = default(VList <LNode>))
        {
            var endMarker = default(TT);

            return(ExprList(ref endMarker, list));
        }
Exemple #51
0
 public void ScanClassBody(VList <LNode> body)
 {
     foreach (var stmt in body)
     {
         int i;
         {
             LNode         altName;
             VList <LNode> attrs, childBody = default(VList <LNode>), parts, rest;
             if ((attrs = stmt.Attrs).IsEmpty | true && stmt.Calls(CodeSymbols.Fn, 3) && stmt.Args[0].IsIdNamed((Symbol)"alt") && (altName = stmt.Args[1]) != null && stmt.Args[2].Calls(CodeSymbols.AltList) && (parts = stmt.Args[2].Args).IsEmpty | true || (attrs = stmt.Attrs).IsEmpty | true && stmt.Calls(CodeSymbols.Fn, 4) && stmt.Args[0].IsIdNamed((Symbol)"alt") && (altName = stmt.Args[1]) != null && stmt.Args[2].Calls(CodeSymbols.AltList) && (parts = stmt.Args[2].Args).IsEmpty | true && stmt.Args[3].Calls(CodeSymbols.Braces) && (childBody = stmt.Args[3].Args).IsEmpty | true)
             {
                 LNode genericAltName = altName;
                 if (altName.CallsMin(CodeSymbols.Of, 1))
                 {
                 }
                 else if (_genericArgs.Count > 0)
                 {
                     genericAltName = LNode.Call(CodeSymbols.Of, LNode.List().Add(altName).AddRange(_genericArgs.ToVList())).SetStyle(NodeStyle.Operator);
                 }
                 var child = new AltType(attrs, genericAltName, LNode.List(), this);
                 child.AddParts(parts);
                 child.ScanClassBody(childBody);
                 _children.Add(child);
             }
             else if ((attrs = stmt.Attrs).IsEmpty | true && (i = attrs.IndexWhere(a => a.IsIdNamed(__alt))) > -1 && stmt.CallsMin(CodeSymbols.Constructor, 3) && stmt.Args[1].IsIdNamed((Symbol)"#this") && stmt.Args[2].Calls(CodeSymbols.AltList) && (rest = new VList <LNode>(stmt.Args.Slice(3))).IsEmpty | true && rest.Count <= 1)
             {
                 parts = stmt.Args[2].Args;
                 attrs.RemoveAt(i);
                 _constructorAttrs.AddRange(attrs);
                 if (rest.Count > 0 && rest[0].Calls(S.Braces))
                 {
                     _extraConstrLogic.AddRange(rest[0].Args);
                 }
                 AddParts(parts);
             }
             else
             {
                 _classBody.Add(stmt);
             }
         }
     }
 }
Exemple #52
0
        LNode Particle(bool isAttribute = false)
        {
            VList <LNode> got_TokenList = default(VList <LNode>);
            Token         lit_lpar      = default(Token);
            Token         lit_rpar      = default(Token);
            LNode         result        = default(LNode);

            // Line 238: ( (TT.BQId|TT.Id) | TT.Literal | TT.SingleQuoteOp TokenList | BracedBlock | SquareBracketList | TT.LParen ExprList TT.RParen )
            switch ((TT)LA0)
            {
            case TT.BQId:
            case TT.Id:
            {
                var id = MatchAny();
                // line 239
                result = F.Id(id).SetStyle(id.Style);
            }
            break;

            case TT.Literal:
            {
                var lit = MatchAny();
                // line 241
                result = F.Literal(lit);
            }
            break;

            case TT.SingleQuoteOp:
            {
                var op = MatchAny();
                got_TokenList = TokenList();
                // line 244
                result = F.Call((Symbol)op.Value, got_TokenList, op.StartIndex, got_TokenList.IsEmpty ? op.EndIndex : got_TokenList.Last.Range.EndIndex);
            }
            break;

            case TT.LBrace:
                result = BracedBlock();
                break;

            case TT.LBrack:
                result = SquareBracketList();
                break;

            case TT.LParen:
            {
                // line 251
                var endMarker = default(TT);
                lit_lpar = MatchAny();
                // line 252
                bool saveParens = !isAttribute && (TT)LA0 != TT.At;
                var  list       = ExprList(ref endMarker);
                lit_rpar = Match((int)TT.RParen);
                // line 255
                if (endMarker != default(TT) || list.Count != 1)
                {
                    result = F.Call(S.Tuple, list, lit_lpar.StartIndex, lit_rpar.EndIndex, lit_lpar.StartIndex, lit_lpar.EndIndex);
                }
                else
                {
                    result = saveParens ? F.InParens(list[0], lit_lpar.StartIndex, lit_rpar.EndIndex) : list[0];
                }
                ;
            }
            break;

            default:
            {
                // line 262
                result = MissingExpr(LT0, "Expected a particle (id, literal, {braces} or (parens)).");
            }
            break;
            }
            return(result);
        }
Exemple #53
0
        /// <summary>Determines whether one Loyc tree "matches" another. This is
        /// different from a simple equality test in that (1) trivia atributes do
        /// not have to match, and (2) the pattern can contain placeholders represented
        /// by calls to $ (the substitution operator) with an identifier as a parameter.
        /// Placeholders match any subtree, and are saved to the <c>captures</c> map.
        /// </summary>
        /// <param name="candidate">A node that you want to compare with a 'pattern'.</param>
        /// <param name="pattern">A syntax tree that may contain placeholders. A
        /// placeholder is a call to the $ operator with one parameter, which must
        /// be either (A) a simple identifier, or (B) the ".." operator with a simple
        /// identifier as its single parameter. Otherwise, the $ operator is treated
        /// literally as something that must exist in <c>candidate</c>). The subtree
        /// in <c>candidate</c> corresponding to the placeholder is saved in
        /// <c>captures</c>.</param>
        /// <param name="captures">A table that maps placeholder names from
        /// <c>pattern</c> to subtrees in <c>candidate</c>. You can set your map to
        /// null and a map will be created for you if necessary. If you already have
        /// a map, you should clear it before calling this method.</param>
        /// <param name="unmatchedAttrs">On return, a list of trivia attributes in
        /// <c>candidate</c> that were not present in <c>pattern</c>.</param>
        /// <returns>true if <c>pattern</c> matches <c>candidate</c>, false otherwise.</returns>
        /// <remarks>
        /// Attributes in patterns are not yet supported.
        /// <para/>
        /// This method supports multi-part captures, which are matched to
        /// placeholders whose identifier either (A) has a #params attribute or
        /// (B) has the unary ".." operator applied to it (for example, if
        /// the placeholder is called p, this is written as <c>$(params p)</c> in
        /// EC#.) A placeholder that looks like this can match multiple arguments or
        /// multiple statements in the <c>candidate</c> (or <i>no</i> arguments, or
        /// no statements), and will become a #splice(...) node in <c>captures</c>
        /// if it matches multiple items. Multi-part captures are often useful for
        /// getting lists of statements before and after some required element,
        /// e.g. <c>{ $(params before); MatchThis($something); $(params after); }</c>
        /// <para/>
        /// If the same placeholder appears twice then the two matching items are
        /// combined into a single output node (calling #splice).
        /// <para/>
        /// If matching is unsuccessful, <c>captures</c> and <c>unmatchedAttrs</c>
        /// may contain irrelevant information gathered during the attempt to match.
        /// <para/>
        /// In EC#, the quote(...) macro can be used to create the LNode object for
        /// a pattern.
        /// </remarks>
        public static bool MatchesPattern(this LNode candidate, LNode pattern, ref MMap <Symbol, LNode> captures, out VList <LNode> unmatchedAttrs)
        {
            // [$capture] (...)
            if (!AttributesMatch(candidate, pattern, ref captures, out unmatchedAttrs))
            {
                return(false);
            }

            // $capture or $(..capture)
            LNode sub = GetCaptureIdentifier(pattern);

            if (sub != null)
            {
                captures = captures ?? new MMap <Symbol, LNode>();
                AddCapture(captures, sub.Name, candidate);
                unmatchedAttrs = VList <LNode> .Empty;               // The attrs (if any) were captured
                return(true);
            }

            var kind = candidate.Kind;

            if (kind != pattern.Kind)
            {
                return(false);
            }

            if (candidate.Name != pattern.Name)
            {
                return(false);
            }
            if (kind == LNodeKind.Literal)
            {
                return(object.Equals(candidate.Value, pattern.Value));
            }
            else if (kind == LNodeKind.Call)
            {
                if (!MatchesPatternNested(candidate.Target, pattern.Target, ref captures, ref unmatchedAttrs))
                {
                    return(false);
                }
                var cArgs = candidate.Args;
                var pArgs = pattern.Args;

                if (pArgs.Count != cArgs.Count && !pArgs.Any(IsParamsCapture))
                {
                    return(false);
                }

                // Scan from the end of the list to the beginning (RVLists is good at this),
                // matching args one-by-one. Use MatchThenParams() in case of $(params capture).
                while (!pArgs.IsEmpty)
                {
                    LNode pArg = pArgs.Pop();
                    if (IsParamsCapture(pArg))
                    {
                        return(MatchThenParams(cArgs, pArgs, pArg, ref captures, ref unmatchedAttrs));
                    }
                    if (cArgs.IsEmpty)
                    {
                        return(false);
                    }
                    if (!MatchesPatternNested(cArgs.Pop(), pArg, ref captures, ref unmatchedAttrs))
                    {
                        return(false);
                    }
                }
                return(true);
            }
            else               // kind == Id
            {
                return(true);
            }
        }
Exemple #54
0
        public VList <LNode> ExprList(ref TokenType endMarker, VList <LNode> list = default(VList <LNode>))
        {
            TT    la0;
            LNode e   = default(LNode);
            Token end = default(Token);

            // line 57
            if ((LT0.Value is string))
            {
                endMarker = TT.EOF;
            }
            // Line 1: ( / TopExpr)
            switch ((TT)LA0)
            {
            case EOF:
            case TT.Comma:
            case TT.Dedent:
            case TT.RBrace:
            case TT.RBrack:
            case TT.RParen:
            case TT.Semicolon:
            {
            }
            break;

            default:
                e = TopExpr();
                break;
            }
            // Line 59: ((TT.Comma|TT.Semicolon) ( / TopExpr))*
            for (;;)
            {
                la0 = (TT)LA0;
                if (la0 == TT.Comma || la0 == TT.Semicolon)
                {
                    end = MatchAny();
                    list.Add(e ?? MissingExpr());
                    CheckEndMarker(ref endMarker, ref end);
                    // Line 62: ( / TopExpr)
                    switch ((TT)LA0)
                    {
                    case EOF:
                    case TT.Comma:
                    case TT.Dedent:
                    case TT.RBrace:
                    case TT.RBrack:
                    case TT.RParen:
                    case TT.Semicolon:
                        // line 62
                        e = null;
                        break;

                    default:
                        e = TopExpr();
                        break;
                    }
                }
                else
                {
                    break;
                }
            }
            if ((e != null || end.Type() == TT.Comma))
            {
                list.Add(e ?? MissingExpr());
            }
            return(list);
        }
Exemple #55
0
 private void PrintArgList(VList <LNode> args, ParenFor kind, Ambiguity flags, bool omitMissingArguments, char separator = ',')
 {
     WriteOpenParen(kind);
     PrintArgs(args, flags, omitMissingArguments, separator);
     WriteCloseParen(kind);
 }
Exemple #56
0
        static bool MatchesPatternNested(LNode candidate, LNode pattern, ref MMap <Symbol, LNode> captures, ref VList <LNode> trivia)
        {
            VList <LNode> unmatchedAttrs;

            if (!MatchesPattern(candidate, pattern, ref captures, out unmatchedAttrs))
            {
                return(false);
            }
            if (unmatchedAttrs.Any(a => !a.IsTrivia))
            {
                return(false);
            }
            trivia.AddRange(unmatchedAttrs);
            return(true);
        }
Exemple #57
0
            void GetPatternComponents(LNode pattern, out LNode propName,
                                      out LNode varBinding, out bool refExistingVar,
                                      out LNode cmpExpr, out LNode isType, out LNode inRange,
                                      out VList <LNode> subPatterns, out VList <LNode> conditions)
            {
                // Format: PropName: is DerivedClass name(...) in Range
                // Here's a typical pattern (case expr):
                //  is Shape(ShapeType.Circle, ref size, Location: p is Point<int>(x, y))
                // When there is an arg list, we decode its Target and return the args.
                //
                // The caller is in charge of stripping out "Property:" prefix, if any,
                // so the most complex pattern that this method considers is something
                // like `expr is Type x(subPatterns) in Range && conds` where `expr` is
                // a varName or $varName to deconstruct, or some expression to test for
                // equality. Assuming it's an equality test, the output will be
                //
                //   varBinding = null
                //   refExistingVar = false
                //   cmpExpr = quote(expr);
                //   isType = quote(Type);
                //   inRange = quote(Range);
                //   conds will have "conds" pushed to the front.
                //
                subPatterns    = VList <LNode> .Empty;
                refExistingVar = pattern.AttrNamed(S.Ref) != null;

                propName = varBinding = cmpExpr = isType = inRange = null;
                // Deconstruct `PropName: pattern` (fun fact: we can't use `matchCode`
                // to detect a named parameter here, because if we write
                // `case { $propName: $subPattern; }:` it is parsed as a goto-label,
                // not as a named parameter.)
                if (pattern.Calls(S.NamedArg, 2) || pattern.Calls(S.Colon, 2))
                {
                    propName = pattern[0]; pattern = pattern[1];
                }
                // Deconstruct `pattern && condition` (iteratively)
                conditions = VList <LNode> .Empty;
                while (pattern.Calls(S.And, 2))
                {
                    conditions.Add(pattern.Args.Last);
                    pattern = pattern.Args[0];
                }

                {
                    LNode lhs;
                    if (pattern.Calls(CodeSymbols.In, 2) && (lhs = pattern.Args[0]) != null && (inRange = pattern.Args[1]) != null || pattern.Calls((Symbol)"in", 2) && (lhs = pattern.Args[0]) != null && (inRange = pattern.Args[1]) != null || pattern.Calls(CodeSymbols.In, 2) && (lhs = pattern.Args[0]) != null && (inRange = pattern.Args[1]) != null)
                    {
                        pattern = lhs;
                    }
                }
                // Deconstruct `PropName is Type` with optional list of subpatterns.
                // In LES let's accept ``PropName `is` (Type `with` (subpatterns))`` instead.
                LNode subpatterns = null;

                {
                    LNode lhs, type;
                    if (pattern.Calls(CodeSymbols.Is, 2) && (lhs = pattern.Args[0]) != null && (type = pattern.Args[1]) != null || pattern.Calls(CodeSymbols.Is, 3) && (lhs = pattern.Args[0]) != null && (type = pattern.Args[1]) != null && (subpatterns = pattern.Args[2]) != null || pattern.Calls((Symbol)"is", 2) && (lhs = pattern.Args[0]) != null && (type = pattern.Args[1]) != null || pattern.Calls((Symbol)"'is", 2) && (lhs = pattern.Args[0]) != null && (type = pattern.Args[1]) != null)
                    {
                        if (subpatterns == null)
                        {
                            if (type.Calls((Symbol)"with", 2) && (isType = type.Args[0]) != null && (subpatterns = type.Args[1]) != null || type.Calls((Symbol)"'with", 2) && (isType = type.Args[0]) != null && (subpatterns = type.Args[1]) != null)
                            {
                            }
                        }
                        if (type.Calls(CodeSymbols.Var, 2) && (isType = type.Args[0]) != null && (varBinding = type.Args[1]) != null)
                        {
                        }
                        else
                        {
                            isType = type;
                        }
                        if (lhs.Calls(S.Substitute, 1))
                        {
                            if (varBinding != null)
                            {
                                _context.Sink.Error(varBinding, "match: cannot bind two variable names to one value");
                            }
                            varBinding = lhs[0];
                        }
                        else if (propName != null)
                        {
                            _context.Sink.Error(varBinding, "match: property name already set to {0}", propName.Name);
                            if (varBinding == null)
                            {
                                varBinding = lhs;                                       // assume it was intended as a variable binding
                            }
                        }
                        if (type.IsIdNamed("")                          // is var x
                            )
                        {
                            isType = null;
                        }
                    }
                    else if (pattern.Calls(CodeSymbols.DotDotDot, 2) || pattern.Calls(CodeSymbols.DotDot, 2) || pattern.Calls(CodeSymbols.DotDotDot, 1) || pattern.Calls(CodeSymbols.DotDot, 1))
                    {
                        inRange = pattern;
                    }
                    else if (pattern.Calls(CodeSymbols.AltList) || pattern.Calls(CodeSymbols.Tuple))
                    {
                        subpatterns = pattern;
                    }
                    else if (pattern.Calls(S.Substitute, 1))
                    {
                        varBinding = pattern[0];
                    }
                    else
                    {
                        cmpExpr = pattern;
                    }
                }
                if (subpatterns != null)
                {
                    if (subpatterns.Calls(S.Tuple) || subpatterns.Calls(S.AltList))
                    {
                        subPatterns = subpatterns.Args;
                    }
                    else
                    {
                        _context.Sink.Error(subpatterns, "match: expected list of subpatterns (at '{0}')", subpatterns);
                    }
                }
                if (cmpExpr != null)
                {
                    if (cmpExpr.IsIdNamed(__))
                    {
                        cmpExpr = null;
                    }
                    else if (refExistingVar && varBinding == null)                              // Treat `ref expr` as var binding
                    {
                        varBinding = cmpExpr;
                        cmpExpr    = null;
                    }
                }
                if (varBinding != null)
                {
                    if (varBinding.AttrNamed(S.Ref) != null)
                    {
                        varBinding     = varBinding.WithoutAttrNamed(S.Ref);
                        refExistingVar = true;
                    }
                    else if (varBinding.IsIdNamed(__))
                    {
                        varBinding = null;
                    }
                    else if (!varBinding.IsId)
                    {
                        _context.Sink.Error(varBinding, "match: expected variable name (at '{0}')", varBinding);
                        varBinding = null;
                    }
                }
            }
Exemple #58
0
        protected LNode TopExpr()
        {
            TT            la0, la1;
            Token         at    = default(Token);
            VList <LNode> attrs = default(VList <LNode>);
            LNode         e     = default(LNode);
            Token         t     = default(Token);

            // Line 91: greedy((TT.At)? TT.LBrack ExprList TT.RBrack)?
            do
            {
                la0 = (TT)LA0;
                if (la0 == TT.At)
                {
                    la1 = (TT)LA(1);
                    if (la1 == TT.LBrack)
                    {
                        goto match1;
                    }
                }
                else if (la0 == TT.LBrack)
                {
                    switch ((TT)LA(1))
                    {
                    case TT.Assignment:
                    case TT.At:
                    case TT.BQString:
                    case TT.Colon:
                    case TT.Comma:
                    case TT.Dot:
                    case TT.Id:
                    case TT.LBrace:
                    case TT.LBrack:
                    case TT.Literal:
                    case TT.LParen:
                    case TT.NormalOp:
                    case TT.Not:
                    case TT.PrefixOp:
                    case TT.PreOrSufOp:
                    case TT.RBrack:
                    case TT.Semicolon:
                    case TT.SpaceLParen:
                        goto match1;
                    }
                }
                break;
match1:
                {
                    // Line 91: (TT.At)?
                    la0 = (TT)LA0;
                    if (la0 == TT.At)
                    {
                        at = MatchAny();
                    }
                    // line 92
                    if (at.Type() == default(TT))
                    {
                        ErrorSink.Write(Severity.Warning, LaIndexToSourcePos(0), "Attribute: expected '@['");
                    }
                    t     = Match((int)TT.LBrack);
                    attrs = ExprList();
                    Match((int)TT.RBrack);
                }
            } while (false);
            // Line 95: (Expr / TT.Id Expr (Particle)*)
            do
            {
                switch ((TT)LA0)
                {
                case TT.Assignment:
                case TT.BQString:
                case TT.Dot:
                case TT.NormalOp:
                case TT.Not:
                case TT.PrefixOp:
                case TT.PreOrSufOp:
                    e = Expr(StartStmt);
                    break;

                case TT.Id:
                {
                    switch ((TT)LA(1))
                    {
                    case TT.Assignment:
                    case TT.BQString:
                    case TT.Dot:
                    case TT.NormalOp:
                        e = Expr(StartStmt);
                        break;

                    case TT.Colon:
                    {
                        if (LA(1 + 1) != (int)TT.Indent)
                        {
                            e = Expr(StartStmt);
                        }
                        else
                        {
                            goto match2;
                        }
                    }
                    break;

                    case EOF:
                    case TT.Comma:
                    case TT.Dedent:
                    case TT.LBrack:
                    case TT.LParen:
                    case TT.Not:
                    case TT.PreOrSufOp:
                    case TT.RBrace:
                    case TT.RBrack:
                    case TT.RParen:
                    case TT.Semicolon:
                        e = Expr(StartStmt);
                        break;

                    default:
                        goto match2;
                    }
                }
                break;

                default:
                    e = Expr(StartStmt);
                    break;
                }
                break;
match2:
                {
                    var id = MatchAny();
                    // line 98
                    var args = VList <LNode> .Empty;
                    args.Add(Expr(P.SuperExpr));
                    // Line 100: (Particle)*
                    for (;;)
                    {
                        switch ((TT)LA0)
                        {
                        case TT.At:
                        case TT.Colon:
                        case TT.Id:
                        case TT.LBrace:
                        case TT.LBrack:
                        case TT.Literal:
                        case TT.LParen:
                        case TT.SpaceLParen:
                        {
                            // line 101
                            if (((TT)LA0 == TT.LParen))
                            {
                                var loc = args[args.Count - 2, args.Last].Range.End;
                                Error(0, "Expected a space before '(' (possibly missing ';' or ',' at {0})", loc);
                            }
                            args.Add(Particle());
                        }
                        break;

                        default:
                            goto stop;
                        }
                    }
                    stop :;
                    // line 108
                    e = MarkSpecial(F.Call(id, args, id.StartIndex, args.Last.Range.EndIndex));
                }
            } while (false);
            if ((t.TypeInt != 0))
            {
                e = e.WithRange(t.StartIndex, e.Range.EndIndex);
            }
            return(e.PlusAttrs(attrs));
        }
Exemple #59
0
        public static LNode unroll(LNode var, VList <LNode> cases, LNode body, IMessageSink sink)
        {
            // Maps identifiers => replacements. The integer counts how many times replacement occurred.
            var replacements = InternalList <Triplet <Symbol, LNode, int> > .Empty;

            if (var.IsId && !var.HasPAttrs())
            {
                replacements.Add(Pair.Create(var.Name, (LNode)LNode.Missing, 0));
            }
            else
            {
                var vars = var.Args;
                if ((var.Calls(S.Tuple) || var.Calls(S.Braces)) && vars.All(a => a.IsId && !a.HasPAttrs()))
                {
                    replacements = new Triplet <Symbol, LNode, int> [vars.Count].AsInternalList();
                    for (int i = 0; i < vars.Count; i++)
                    {
                        replacements.InternalArray[i].A = vars[i].Name;

                        // Check for duplicate names
                        for (int j = 0; j < i; j++)
                        {
                            if (replacements[i].A == replacements[j].A && replacements[i].A.Name != "_")
                            {
                                sink.Error(vars[i], "Duplicate name in the left-hand tuple");                                 // non-fatal
                            }
                        }
                    }
                }
                else
                {
                    return(Reject(sink, var, "The left-hand side of 'in' should be a simple identifier or a tuple of simple identifiers."));
                }
            }

            UnrollCtx ctx = new UnrollCtx {
                Replacements = replacements
            };
            WList <LNode> output = new WList <LNode>();
            int iteration        = 0;
            foreach (LNode replacement in cases)
            {
                iteration++;
                bool tuple = replacement.Calls(S.Tuple) || replacement.Calls(S.Braces);
                int  count = tuple ? replacement.ArgCount : 1;
                if (replacements.Count != count)
                {
                    sink.Error(replacement, "iteration {0}: Expected {1} replacement items, got {2}", iteration, replacements.Count, count);
                    if (count < replacements.Count)
                    {
                        continue;                         // too few
                    }
                }
                for (int i = 0; i < replacements.Count; i++)
                {
                    replacements.InternalArray[i].B = tuple ? replacement.Args[i] : replacement;
                }

                if (body.Calls(S.Braces))
                {
                    foreach (LNode stmt in body.Args)
                    {
                        output.Add(ctx.Replace(stmt).Value);
                    }
                }
                else
                {
                    output.Add(ctx.Replace(body).Value);
                }
            }

            foreach (var r in replacements)
            {
                if (r.C == 0 && !r.A.Name.StartsWith("_"))
                {
                    sink.Write(Severity.Warning, var, "Replacement variable '{0}' was never used", r.A);
                }
            }

            return(body.With(S.Splice, output.ToVList()));
        }
Exemple #60
0
        LNode FinishPrimaryExpr(LNode e)
        {
            TT            la0;
            VList <LNode> list = default(VList <LNode>);

            // Line 148: ( TT.LParen ExprList TT.RParen | TT.Not (TT.LParen ExprList TT.RParen / Expr) | TT.LBrack ExprList TT.RBrack )
            la0 = (TT)LA0;
            if (la0 == TT.LParen)
            {
                // line 148
                var endMarker = default(TokenType);
                Skip();
                list = ExprList(ref endMarker);
                var c = Match((int)TT.RParen);
                // line 151
                e = MarkCall(F.Call(e, list, e.Range.StartIndex, c.EndIndex));
                if ((endMarker == TT.Semicolon))
                {
                    e.Style = NodeStyle.Statement | NodeStyle.Alternate;
                }
            }
            else if (la0 == TT.Not)
            {
                Skip();
                // line 156
                var args = new VList <LNode> {
                    e
                };
                int endIndex;
                // Line 157: (TT.LParen ExprList TT.RParen / Expr)
                la0 = (TT)LA0;
                if (la0 == TT.LParen)
                {
                    Skip();
                    args = ExprList(args);
                    var c = Match((int)TT.RParen);
                    // line 157
                    endIndex = c.EndIndex;
                }
                else
                {
                    var T = Expr(P.Primary);
                    // line 158
                    args.Add(T);
                    endIndex = T.Range.EndIndex;
                }
                // line 160
                e = F.Call(S.Of, args, e.Range.StartIndex, endIndex).SetStyle(NodeStyle.Operator);
            }
            else
            {
                // line 162
                var args = new VList <LNode> {
                    e
                };
                Match((int)TT.LBrack);
                args = ExprList(args);
                var c = Match((int)TT.RBrack);
                // line 164
                e = F.Call(S.IndexBracks, args, e.Range.StartIndex, c.EndIndex).SetStyle(NodeStyle.Operator);
            }
            // line 166
            return(e);
        }