public async Task <Dafny.Program> ParseAsync(TextDocumentItem document, ErrorReporter errorReporter, CancellationToken cancellationToken) { await _mutex.WaitAsync(cancellationToken); try { // Ensure that the statically kept scopes are empty when parsing a new document. Type.ResetScopes(); var module = new LiteralModuleDecl(new DefaultModuleDecl(), null); var builtIns = new BuiltIns(); var parseErrors = Parser.Parse( document.Text, document.Uri.GetFileSystemPath(), // We use the full path as filename so we can better re-construct the DocumentUri for the definition lookup. document.Uri.GetFileSystemPath(), module, builtIns, errorReporter ); if (parseErrors != 0) { _logger.LogDebug("encountered {} errors while parsing {}", parseErrors, document.Uri); } if (!TryParseIncludesOfModule(module, builtIns, errorReporter)) { _logger.LogDebug("encountered error while parsing the includes of {}", document.Uri); } // TODO Remove PoC workaround: the file system path is used as a program name to return(new Dafny.Program(document.Uri.GetFileSystemPath(), module, builtIns, errorReporter)); } finally { _mutex.Release(); } }
public override void Init() { base.Init(); BuiltIns.AddMethod(MtPrint, "print", 1); BuiltIns.AddMethod(MtFalse, "false"); BuiltIns.AddMethod(MtTrue, "true"); BuiltIns.AddMethod(MtIdentity, "identity", 1); BuiltIns.AddMethod(MtSleep, "sleep", 1, 2); BuiltIns.AddMethod(MtAdd, "add", 1); BuiltIns.AddMethod(MtMult, "mult", 1); BuiltIns.AddMethod(MtSubt, "subt", 1); BuiltIns.AddMethod(MtDiv, "div", 1); BuiltIns.AddMethod(MtZero, "zero", 1); BuiltIns.AddMethod(MtCar, "car", 1, 1); BuiltIns.AddMethod(MtCdr, "cdr", 1, 1); BuiltIns.AddMethod(MtMap, "map", 2, 2); BuiltIns.AddMethod(MtStringStreamCreate, "str_stream", 1, 1); BuiltIns.AddMethod(MtUriStreamCreate, "uri_stream", 1, 1); BuiltIns.AddMethod(MtStreamsClose, "close_stream", 1); BuiltIns.AddMethod(MtWait, "wait", 1); BuiltIns.AddMethod(MtLength, "length", 1); BuiltIns.AddMethod(MtEquals, "equals", 2); BuiltIns.AddMethod(MtGreater, "greater", 2); BuiltIns.AddMethod(MtSliceUntil, "slice_until", 2); BuiltIns.AddMethod(MtSliceFrom, "slice_from", 2); BuiltIns.AddMethod(MtCons, "cons", 2); BuiltIns.AddMethod(MtAnd, "and", 2); BuiltIns.AddMethod(MtNot, "not", 1); #if !SILVERLIGHT // JSON BuiltIns.AddMethod(MtJsonParse, "json_parse", 1); // HTTP Server BuiltIns.AddMethod(MtHttpServerCreate, "http_server", 1); BuiltIns.AddMethod(MtHttpServerStart, "http_server_start", 1); BuiltIns.AddMethod(MtHttpServerStop, "http_server_stop", 1); BuiltIns.AddMethod(MtHttpSetCode, "http_set_code", 2, 2); BuiltIns.AddMethod(MtHttpSetContentType, "http_set_content_type", 2, 2); BuiltIns.AddMethod(MtHttpStream, "http_stream", 1, 1); BuiltIns.AddMethod(MtHttpEnd, "http_end", 1, 1); #endif // TODO // Get request/response stream // Get/Set request/response header value // MORE ... // TODO Add insert, append, concat // TODO Add object literals // TODO Add streams literals? // TODO Add map, filter, reduce // TODO Add sorting examples // TODO Add quote (for lazy evaluation of MtResults) // TODO Add flow control instructions (continuations, exceptions, ...) // TODO Add signaling, waiting // TODO Add compose(f, g) // TODO Add curry }
// TODO The following methods are based on the ones from DafnyPipeline/DafnyMain.cs. // It could be convenient to adapt them in the main-repo so location info could be extracted. public bool TryParseIncludesOfModule(ModuleDecl module, BuiltIns builtIns, ErrorReporter errorReporter) { var errors = new Errors(errorReporter); // Issue #40: // A HashSet must not be used here since equals treats A included by B not equal to A included by C. // In contrast, the compareTo-Method treats them as the same. var resolvedIncludes = new SortedSet <Include>(); var dependencyMap = new DependencyMap(); dependencyMap.AddIncludes(resolvedIncludes); bool newIncludeParsed = true; while (newIncludeParsed) { newIncludeParsed = false; // Parser.Parse appears to modify the include list; thus, we create a copy to avoid concurrent modifications. var moduleIncludes = new List <Include>(((LiteralModuleDecl)module).ModuleDef.Includes); dependencyMap.AddIncludes(moduleIncludes); foreach (var include in moduleIncludes) { bool isNewInclude = resolvedIncludes.Add(include); if (isNewInclude) { newIncludeParsed = true; if (!TryParseInclude(include, module, builtIns, errorReporter, errors)) { return(false); } } } } return(true); }
/// <summary> /// Returns null on success, or an error string otherwise. /// </summary> public static string ParseOnly(IList <string /*!*/> /*!*/ fileNames, string /*!*/ programName, out Program program) { Contract.Requires(programName != null); Contract.Requires(fileNames != null); program = null; ModuleDecl module = new LiteralModuleDecl(new DefaultModuleDecl(), null); BuiltIns builtIns = new BuiltIns(); foreach (string dafnyFileName in fileNames) { Contract.Assert(dafnyFileName != null); string err = ParseFile(dafnyFileName, Token.NoToken, module, builtIns, new Errors(new ConsoleErrorReporter())); if (err != null) { return(err); } } if (!DafnyOptions.O.DisallowIncludes) { string errString = ParseIncludes(module, builtIns, fileNames, new Errors(new ConsoleErrorReporter())); if (errString != null) { return(errString); } } program = new Program(programName, module, builtIns, new ConsoleErrorReporter()); return(null); }
public void TestTransformStampedMessage() { Assert.True(BuiltIns.GetMessageType <MyTransformStamped>() == MyTransformStamped.RosMessageType); Assert.True(BuiltIns.GetMd5Sum <MyTransformStamped>() == BuiltIns.GetMd5Sum <TransformStamped>()); time now = time.Now(); TransformStamped real = new TransformStamped() { Header = new Header(1, now, "Frame"), ChildFrameId = "Abcd", Transform = Transform.Identity }; MyTransformStamped wrapped = new MyTransformStamped() { Header = new Header(1, now, "Frame"), ChildFrameId = "Abcd", Transform = Transform.Identity }; byte[] messageBytes = real.SerializeToArray(); byte[] otherMessageBytes = wrapped.SerializeToArray(); Assert.True(messageBytes.SequenceEqual(otherMessageBytes)); var otherWrapped = wrapped.DeserializeFromArray(messageBytes); Assert.True(wrapped.Header == real.Header); Assert.True(wrapped.ChildFrameId == real.ChildFrameId); Assert.True(wrapped.Transform == real.Transform); }
public RosServiceDefinition() { try { RosType = BuiltIns.GetServiceType <T>(); } catch (RosInvalidMessageException) { throw new RosIncompleteWrapperException( $"Type '{typeof(T).Name}' must have a string constant named RosMessageType. " + "It should also be tagged with the attribute [MessageName]."); } const string serviceSeparator = "---"; RosDefinition = RosRequestWrapper <T, TRequest, TResponse> .RosDefinition + "\n" + serviceSeparator + "\n" + RosResponseWrapper <T, TRequest, TResponse> .RosDefinition + "\n"; RosMessageMd5 = RosWrapperBase.CreateMd5( RosRequestWrapper <T, TRequest, TResponse> .RosInputForMd5 + RosResponseWrapper <T, TRequest, TResponse> .RosInputForMd5); var alreadyWritten = new HashSet <Type>(); RosDependencies = RosDefinition + RosSerializableDefinition <TRequest> .CreatePartialDependencies(alreadyWritten) + RosSerializableDefinition <TResponse> .CreatePartialDependencies(alreadyWritten); }
public Program ParseAndTypeCheck(bool runResolver) { var errorReporter = new ConsoleErrorReporter(); var module = new LiteralModuleDecl(new DefaultModuleDecl(), null); var builtIns = new BuiltIns(); var parseErrors = new Errors(errorReporter); var errorCount = Parser.Parse(_snapshot.GetText(), _filename, _filename, module, builtIns, parseErrors); var errString = Main.ParseIncludes(module, builtIns, new List <string>(), parseErrors); if (errorCount != 0 || errString != null) { return(null); } var program = new Program(_filename, module, builtIns, errorReporter); if (!runResolver) { return(program); } var r = new Resolver(program); r.ResolveProgram(program); return(errorReporter.Count(ErrorLevel.Error) == 0 ? program : null); }
public ProofState(Program program) { Contract.Requires(program != null); // get a new program instance Datatypes = new Dictionary <string, DatatypeDecl>(); _topLevelClasses = new List <TopLevelClassDeclaration>(); var files = new List <DafnyFile> { new DafnyFile(program.FullName) }; if (program.Raw == null) { Main.Parse(files, program.Name, new ConsoleErrorReporter(), out _original); } else { /* * System.IO.StreamReader reader = new System.IO.StreamReader(program.FullName); * var s = Microsoft.Boogie.ParserHelper.Fill(reader, new List<string>()); * program.Raw = s; */ var reporter = new ConsoleErrorReporter(); ModuleDecl module = new LiteralModuleDecl(new DefaultModuleDecl(), null); BuiltIns builtIns = new BuiltIns(); Parser.Parse(program.Raw, program.FullName, program.FullName, module, builtIns, reporter); _original = new Program(program.FullName, module, builtIns, reporter); } // fill state FillStaticState(program); }
private bool TryParseInclude(Include include, ModuleDecl module, BuiltIns builtIns, ErrorReporter errorReporter, Errors errors) { try { var dafnyFile = new DafnyFile(include.includedFilename); int errorCount = Parser.Parse( useStdin: false, dafnyFile.SourceFileName, include, module, builtIns, errors, verifyThisFile: false, compileThisFile: false ); if (errorCount != 0) { errorReporter.Error(MessageSource.Parser, include.tok, $"{errorCount} parse error(s) detected in {include.includedFilename}"); return(false); } } catch (IllegalDafnyFile e) { errorReporter.Error(MessageSource.Parser, include.tok, $"Include of file {include.includedFilename} failed."); _logger.LogDebug(e, "encountered include of illegal dafny file {}", include.includedFilename); return(false); } catch (IOException e) { errorReporter.Error(MessageSource.Parser, include.tok, $"Unable to open the include {include.includedFilename}."); _logger.LogDebug(e, "could not open file {}", include.includedFilename); return(false); } return(true); }
public void Test() { ErrorReporter reporter = new ConsoleErrorReporter(); var options = new DafnyOptions(reporter); options.DafnyPrelude = "../../../../../Binaries/DafnyPrelude.bpl"; DafnyOptions.Install(options); var programString = @"trait Trait<A, B> { }"; ModuleDecl module = new LiteralModuleDecl(new DefaultModuleDecl(), null); Microsoft.Dafny.Type.ResetScopes(); BuiltIns builtIns = new BuiltIns(); Parser.Parse(programString, "virtual", "virtual", module, builtIns, reporter); var dafnyProgram = new Program("programName", module, builtIns, reporter); Main.Resolve(dafnyProgram, reporter); foreach (var prog in Translator.Translate(dafnyProgram, dafnyProgram.reporter)) { var writer = new StringWriter(); var tokenWriter = new Bpl.TokenTextWriter("virtual", writer, true); prog.Item2.Emit(tokenWriter); var parseErrorCount = Bpl.Parser.Parse(writer.ToString(), "virtualBoogie", out var boogieProgram); Assert.Equal(0, parseErrorCount); } }
public void TestFindingMessage() { Assert.NotNull(BuiltIns.TryGetTypeFromMessageName("std_msgs/Header")); Assert.Null(BuiltIns.TryGetTypeFromMessageName("std_msgs/NonExistingMessage")); // these two are equivalent Assert.NotNull(BuiltIns.TryGetTypeFromMessageName("dummy_namespace/DummyMessage", "Iviz.UtilsTests")); Assert.NotNull(BuiltIns.TryGetTypeFromMessageName("DummyNamespace/DummyMessage", "Iviz.UtilsTests")); }
public void RegisterBuiltIn(string name, ClrFunction clrFunction) { if (BuiltIns.ContainsKey(name)) { throw new InvalidOperationException($"Built-in function '{name}' has already been registered."); } BuiltIns.Add(name, clrFunction); }
public ServiceInfo(string callerId, string service, T?generator = default) : this( callerId, service, BuiltIns.GetMd5Sum <T>(), BuiltIns.GetServiceType <T>(), generator ) { }
/// <summary> /// Returns null on success, or an error string otherwise. /// </summary> public static string ParseCheck(IList <string /*!*/> /*!*/ fileNames, string /*!*/ programName, ErrorReporter reporter, out Program program) //modifies Bpl.CommandLineOptions.Clo.XmlSink.*; { Contract.Requires(programName != null); Contract.Requires(fileNames != null); program = null; ModuleDecl module = new LiteralModuleDecl(new DefaultModuleDecl(), null); BuiltIns builtIns = new BuiltIns(); foreach (string dafnyFileName in fileNames) { Contract.Assert(dafnyFileName != null); if (Bpl.CommandLineOptions.Clo.XmlSink != null && Bpl.CommandLineOptions.Clo.XmlSink.IsOpen) { Bpl.CommandLineOptions.Clo.XmlSink.WriteFileFragment(dafnyFileName); } if (Bpl.CommandLineOptions.Clo.Trace) { Console.WriteLine("Parsing " + dafnyFileName); } string err = ParseFile(dafnyFileName, Bpl.Token.NoToken, module, builtIns, new Errors(reporter)); if (err != null) { return(err); } } if (!DafnyOptions.O.DisallowIncludes) { string errString = ParseIncludes(module, builtIns, fileNames, new Errors(reporter)); if (errString != null) { return(errString); } } program = new Program(programName, module, builtIns, reporter); MaybePrintProgram(program, DafnyOptions.O.DafnyPrintFile, false); if (Bpl.CommandLineOptions.Clo.NoResolve || Bpl.CommandLineOptions.Clo.NoTypecheck) { return(null); } Dafny.Resolver r = new Dafny.Resolver(program); r.ResolveProgram(program); MaybePrintProgram(program, DafnyOptions.O.DafnyPrintResolvedFile, true); if (reporter.Count(ErrorLevel.Error) != 0) { return(string.Format("{0} resolution/type errors detected in {1}", reporter.Count(ErrorLevel.Error), program.Name)); } return(null); // success }
public TopicInfo(string callerId, string topic, IDeserializable <T> generator) : this( BuiltIns.DecompressDependencies(generator.GetType()), callerId, topic, BuiltIns.GetMd5Sum(generator.GetType()), BuiltIns.GetMessageType(generator.GetType()), generator ) { }
public TopicInfo(string callerId, string topic) : this( BuiltIns.DecompressDependencies <T>(), callerId, topic, BuiltIns.GetMd5Sum <T>(), BuiltIns.GetMessageType <T>(), null ) { }
public override void Init() { base.Init(); //add built-in methods, special form IIF, import Math and Environment methods BuiltIns.AddMethod(BuiltInPrintMethod, "print"); BuiltIns.AddMethod(BuiltInFormatMethod, "format"); BuiltIns.AddSpecialForm(SpecialFormsLibrary.Iif, "iif", 3, 3); BuiltIns.ImportStaticMembers(typeof(System.Math)); BuiltIns.ImportStaticMembers(typeof(Environment)); }
public virtual Binding BindSymbolForWrite(BindingRequest request) { var scope = request.Thread.CurrentScope; var existingSlot = scope.Info.GetSlot(request.Symbol); //1. If new only, check it does not exist yet, create and return it if (request.Flags.IsSet(BindingRequestFlags.NewOnly)) { if (existingSlot != null) { request.Thread.ThrowScriptError("Variable {0} already exists.", request.Symbol); } var newSlot = scope.AddSlot(request.Symbol); return(new SlotBinding(newSlot, request.FromNode, request.FromScopeInfo)); } //2. If exists, then return it if (existingSlot != null && request.Flags.IsSet(BindingRequestFlags.ExistingOrNew)) { //TODO: For external client, check that slot is actually public or exported return(new SlotBinding(existingSlot, request.FromNode, request.FromScopeInfo)); } //3. Check external module imports foreach (var imp in request.FromModule.Imports) { var result = imp.Bind(request); if (result != null) { return(result); } } //4. If nothing found, create new slot in current scope if (request.Flags.IsSet(BindingRequestFlags.ExistingOrNew)) { var newSlot = scope.AddSlot(request.Symbol); return(new SlotBinding(newSlot, request.FromNode, request.FromScopeInfo)); } //5. Check built-in methods var builtIn = BuiltIns.Bind(request); if (builtIn != null) { return(builtIn); } //6. If still not found, return null. return(null); }
public static string ParseIncludes(ModuleDecl module, BuiltIns builtIns, IList <string> excludeFiles, Errors errs) { SortedSet <Include> includes = new SortedSet <Include>(new IncludeComparer()); DependencyMap dmap = new DependencyMap(); foreach (string fileName in excludeFiles) { includes.Add(new Include(null, null, fileName)); } dmap.AddIncludes(includes); bool newlyIncluded; do { newlyIncluded = false; List <Include> newFilesToInclude = new List <Include>(); dmap.AddIncludes(((LiteralModuleDecl)module).ModuleDef.Includes); foreach (Include include in ((LiteralModuleDecl)module).ModuleDef.Includes) { bool isNew = includes.Add(include); if (isNew) { newlyIncluded = true; newFilesToInclude.Add(include); } } foreach (Include include in newFilesToInclude) { DafnyFile file; try { file = new DafnyFile(include.includedFilename); } catch (IllegalDafnyFile) { return(String.Format("Include of file \"{0}\" failed.", include.includedFilename)); } string ret = ParseFile(file, include, module, builtIns, errs, false); if (ret != null) { return(ret); } } } while (newlyIncluded); if (DafnyOptions.O.PrintIncludesMode != DafnyOptions.IncludesModes.None) { dmap.PrintMap(); } return(null); // Success }
public static string Parse(IList <DafnyFile> files, string programName, ErrorReporter reporter, out Program program) { Contract.Requires(programName != null); Contract.Requires(files != null); program = null; ModuleDecl module = new LiteralModuleDecl(new DefaultModuleDecl(), null); BuiltIns builtIns = new BuiltIns(); foreach (DafnyFile dafnyFile in files) { Contract.Assert(dafnyFile != null); if (Bpl.CommandLineOptions.Clo.XmlSink != null && Bpl.CommandLineOptions.Clo.XmlSink.IsOpen) { Bpl.CommandLineOptions.Clo.XmlSink.WriteFileFragment(dafnyFile.FilePath); } if (Bpl.CommandLineOptions.Clo.Trace) { Console.WriteLine("Parsing " + dafnyFile.FilePath); } string err = ParseFile(dafnyFile, null, module, builtIns, new Errors(reporter)); if (err != null) { return(err); } } if (!(DafnyOptions.O.DisallowIncludes || DafnyOptions.O.PrintIncludesMode == DafnyOptions.IncludesModes.Immediate)) { string errString = ParseIncludes(module, builtIns, DafnyFile.fileNames(files), new Errors(reporter)); if (errString != null) { return(errString); } } if (DafnyOptions.O.PrintIncludesMode == DafnyOptions.IncludesModes.Immediate) { DependencyMap dmap = new DependencyMap(); dmap.AddIncludes(((LiteralModuleDecl)module).ModuleDef.Includes); dmap.PrintMap(); } program = new Program(programName, module, builtIns, reporter); MaybePrintProgram(program, DafnyOptions.O.DafnyPrintFile, false); return(null); // success }
public Sender([NotNull] string topic) { if (string.IsNullOrWhiteSpace(topic)) { throw new ArgumentException("Invalid topic!", nameof(topic)); } Topic = topic; Type = BuiltIns.GetMessageType(typeof(T)); Logger.Info($"Advertising <b>{topic}</b> <i>[{Type}]</i>."); GameThread.EverySecond += UpdateStats; Connection.Advertise(this); }
/// <summary> /// Invokes Dafny parser on the physical file provided to this instance. /// This will find lexer errors. /// </summary> private bool Parse() { ModuleDecl module = new LiteralModuleDecl(new Microsoft.Dafny.DefaultModuleDecl(), null); BuiltIns builtIns = new BuiltIns(); var success = Microsoft.Dafny.Parser.Parse(_file.Sourcecode, _file.Filepath, _file.Filepath, null, module, builtIns, new Microsoft.Dafny.Errors(_reporter)) == 0 && Microsoft.Dafny.Main.ParseIncludes(module, builtIns, new List <string>(), new Microsoft.Dafny.Errors(_reporter)) == null; if (success) { _dafnyProgram = new Microsoft.Dafny.Program(_file.Filepath, module, builtIns, _reporter); _status = TranslationStatus.Parsed; } return(success); }
private static Program CreateProgramFromFileName(string fileName) { var nameStart = fileName.LastIndexOf('\\') + 1; var programName = fileName.Substring(nameStart, fileName.Length - nameStart); ModuleDecl module = new LiteralModuleDecl(new DefaultModuleDecl(), null); var builtIns = new BuiltIns(); Parser.Parse(fileName, module, builtIns, new Errors(Reporter)); var program = new Program(programName, module, builtIns, Reporter); return(program); }
public void TestInteractiveMarkerMessage() { Assert.True(BuiltIns.GetMessageType(typeof(MyInteractiveMarker)) == MyInteractiveMarker.RosMessageType); Console.WriteLine(MyInteractiveMarker.RosDefinition); Assert.True( BuiltIns.GetMd5Sum(typeof(MyInteractiveMarker)) == BuiltIns.GetMd5Sum(typeof(InteractiveMarker))); time now = time.Now(); var real = new InteractiveMarker() { Pose = Pose.Identity, Name = "Abcd", Description = "Efgh", MenuEntries = new MenuEntry[] { new(), new() },
static void TestNameEntityRecognizer() { string text = "WASHINGTON -- In the wake of a string of abuses by New York police officers in the 1990s, Loretta E. Lynch, " + "the top federal prosecutor in Brooklyn, spoke forcefully about the pain of a broken trust that African-Americans " + "felt and said the responsibility for repairing generations of miscommunication and mistrust fell to law enforcement."; var tokens = Nltk.Tokenize.WordTokenize(text); var posTaggedWords = Nltk.PosTag(tokens.AsNet); // NOTE: This operation requires NumPy library for IronPython var neChunks = Nltk.NeChunk(posTaggedWords); BuiltIns.Print($"NER output for text: '{text}'"); BuiltIns.Print(neChunks); }
/// <summary> /// Returns null on success, or an error string otherwise. /// </summary> public string ParseCheck(IList <string /*!*/> /*!*/ fileNames, string /*!*/ programName, out Microsoft.Dafny.Program program) //modifies Bpl.CommandLineOptions.Clo.XmlSink.*; { //Debug.WriteLine("ACTION: Parsing Dafny program"); Contract.Requires(programName != null); Contract.Requires(fileNames != null); program = null; ModuleDecl module = new LiteralModuleDecl(new DefaultModuleDecl(), null); BuiltIns builtIns = new BuiltIns(); foreach (string dafnyFileName in fileNames) { Contract.Assert(dafnyFileName != null); if (Bpl.CommandLineOptions.Clo.XmlSink != null && Bpl.CommandLineOptions.Clo.XmlSink.IsOpen) { Bpl.CommandLineOptions.Clo.XmlSink.WriteFileFragment(dafnyFileName); } if (Bpl.CommandLineOptions.Clo.Trace) { Console.WriteLine("Parsing " + dafnyFileName); } string err = ParseFile(dafnyFileName, Bpl.Token.NoToken, module, builtIns, new Errors(new ConsoleErrorReporter())); if (err != null) { return(err); } } if (!DafnyOptions.O.DisallowIncludes) { string errString = ParseIncludes(module, builtIns, fileNames, new Errors(new ConsoleErrorReporter())); if (errString != null) { return(errString); } } program = new Microsoft.Dafny.Program(programName, module, builtIns, new ConsoleErrorReporter()); if (Bpl.CommandLineOptions.Clo.NoResolve || Bpl.CommandLineOptions.Clo.NoTypecheck) { return(null); } Debug.WriteLine("SUCCESS: Parsing Dafny Program"); return(null); }
public Repl() { this.parser = new Parser(); this.globalSpace = new SymbolSpace(null); this.globalSpace.Bind("*global", new SymbolSpaceItem(this.globalSpace)); var trueItem = new ValueItem(ItemType.Bool, true); var falseItem = new ValueItem(ItemType.Bool, false); this.globalSpace.Bind("*true", trueItem); this.globalSpace.Bind("*t", trueItem); this.globalSpace.Bind("*false", falseItem); this.globalSpace.Bind("*f", falseItem); BuiltIns.SetupBuiltins(this.globalSpace); }
public Program ParseAndTypeCheck(bool runResolver) { var errorReporter = new ConsoleErrorReporter(); var module = new LiteralModuleDecl(new DefaultModuleDecl(), null); var builtIns = new BuiltIns(); var parseErrors = new Errors(errorReporter); var errorCount = Parser.Parse(_snapshot.GetText(), _filename, _filename, module, builtIns, parseErrors); var errString = Main.ParseIncludes(module, builtIns, new List<string>(), parseErrors); if (errorCount != 0 || errString != null) return null; var program = new Program(_filename, module, builtIns, errorReporter); if (!runResolver) return program; var r = new Resolver(program); r.ResolveProgram(program); return errorReporter.Count(ErrorLevel.Error) == 0 ? program : null; }
Bpl.Expr ArrayLength(Bpl.IToken tok, Bpl.Expr arr, int totalDims, int dim) { Contract.Requires(tok != null); Contract.Requires(arr != null); Contract.Requires(1 <= totalDims); Contract.Requires(0 <= dim && dim < totalDims); string name = "_System." + BuiltIns.ArrayClassName(totalDims) + ".Length"; if (totalDims != 1) { name += dim; } return(new Bpl.NAryExpr(tok, new Bpl.FunctionCall(new Bpl.IdentifierExpr(tok, name, Bpl.Type.Int)), new List <Bpl.Expr> { arr })); }
/// <summary> /// Parse a string read (from a certain file) to a Dafny Program /// </summary> public static Program?Parse(string source, string fileName = "") { ModuleDecl module = new LiteralModuleDecl(new DefaultModuleDecl(), null); var builtIns = new BuiltIns(); var reporter = new ConsoleErrorReporter(); var success = Parser.Parse(source, fileName, fileName, null, module, builtIns, new Errors(reporter)) == 0 && Microsoft.Dafny.Main.ParseIncludes(module, builtIns, new List <string>(), new Errors(reporter)) == null; Program?program = null; if (success) { program = new Program(fileName, module, builtIns, reporter); } new Resolver(program).ResolveProgram(program); return(program); }
IEnumerable <BoogieProgram> GetBoogie(string dafnyProgramText) { var module = new LiteralModuleDecl(new DefaultModuleDecl(), null); var fullFilePath = "foo"; Microsoft.Dafny.Type.ResetScopes(); var builtIns = new BuiltIns(); var errorReporter = new ConsoleErrorReporter(); var parseResult = Parser.Parse(dafnyProgramText, fullFilePath, "foo", module, builtIns, errorReporter); Assert.Equal(0, parseResult); var dafnyProgram = new Microsoft.Dafny.Program(fullFilePath, module, builtIns, errorReporter); Main.Resolve(dafnyProgram, errorReporter); var boogiePrograms = Translator.Translate(dafnyProgram, errorReporter).Select(t => t.Item2); return(boogiePrograms); }
// the real work public Parser(Scanner/*!*/ scanner, Errors/*!*/ errors, ModuleDecl module, BuiltIns builtIns, bool verifyThisFile=true) : this(scanner, errors) { // initialize readonly fields dummyExpr = new LiteralExpr(Token.NoToken); dummyRhs = new ExprRhs(dummyExpr, null); dummyFrameExpr = new FrameExpression(dummyExpr.tok, dummyExpr, null); dummyStmt = new ReturnStmt(Token.NoToken, Token.NoToken, null); theModule = module; theBuiltIns = builtIns; theVerifyThisFile = verifyThisFile; }
void CompileBuiltIns(BuiltIns builtIns, TextWriter wr) { wr.WriteLine("namespace Dafny {"); Indent(IndentAmount, wr); wr.WriteLine("public partial class Helpers {"); foreach (var decl in builtIns.SystemModule.TopLevelDecls) { if (decl is ArrayClassDecl) { int dims = ((ArrayClassDecl)decl).Dims; // public static T[,] InitNewArray2<T>(BigInteger size0, BigInteger size1) { Indent(3 * IndentAmount, wr); wr.Write("public static T["); RepeatWrite(wr, dims, "", ","); wr.Write("] InitNewArray{0}<T>(", dims); RepeatWrite(wr, dims, "BigInteger size{0}", ", "); wr.WriteLine(") {"); // int s0 = (int)size0; for (int i = 0; i < dims; i++) { Indent(4 * IndentAmount, wr); wr.WriteLine("int s{0} = (int)size{0};", i); } // T[,] a = new T[s0, s1]; Indent(4 * IndentAmount, wr); wr.Write("T["); RepeatWrite(wr, dims, "", ","); wr.Write("] a = new T["); RepeatWrite(wr, dims, "s{0}", ","); wr.WriteLine("];"); // BigInteger[,] b = a as BigInteger[,]; Indent(4 * IndentAmount, wr); wr.Write("BigInteger["); RepeatWrite(wr, dims, "", ","); wr.Write("] b = a as BigInteger["); RepeatWrite(wr, dims, "", ","); wr.WriteLine("];"); // if (b != null) { Indent(4 * IndentAmount, wr); wr.WriteLine("if (b != null) {"); // BigInteger z = new BigInteger(0); Indent(5 * IndentAmount, wr); wr.WriteLine("BigInteger z = new BigInteger(0);"); // for (int i0 = 0; i0 < s0; i0++) // for (int i1 = 0; i1 < s1; i1++) for (int i = 0; i < dims; i++) { Indent((5+i) * IndentAmount, wr); wr.WriteLine("for (int i{0} = 0; i{0} < s{0}; i{0}++)", i); } // b[i0,i1] = z; Indent((5+dims) * IndentAmount, wr); wr.Write("b["); RepeatWrite(wr, dims, "i{0}", ","); wr.WriteLine("] = z;"); // } Indent(4 * IndentAmount, wr); wr.WriteLine("}"); // return a; Indent(4 * IndentAmount, wr); wr.WriteLine("return a;"); // } Indent(3 * IndentAmount, wr); wr.WriteLine("}"); // end of method } } Indent(IndentAmount, wr); wr.WriteLine("}"); // end of class Helpers wr.WriteLine("}"); // end of namespace }
///<summary> /// Parses top-level things (modules, classes, datatypes, class members) /// and appends them in appropriate form to "module". /// Returns the number of parsing errors encountered. /// Note: first initialize the Scanner with the given Errors sink. ///</summary> public static int Parse(string/*!*/ s, string/*!*/ fullFilename, string/*!*/ filename, ModuleDecl module, BuiltIns builtIns, Errors/*!*/ errors, bool verifyThisFile=true) { Contract.Requires(s != null); Contract.Requires(filename != null); Contract.Requires(module != null); Contract.Requires(errors != null); byte[]/*!*/ buffer = cce.NonNull( UTF8Encoding.Default.GetBytes(s)); MemoryStream ms = new MemoryStream(buffer,false); Scanner scanner = new Scanner(ms, errors, fullFilename, filename); Parser parser = new Parser(scanner, errors, module, builtIns, verifyThisFile); parser.Parse(); return parser.errors.ErrorCount; }
///<summary> /// Parses top-level things (modules, classes, datatypes, class members) /// and appends them in appropriate form to "module". /// Returns the number of parsing errors encountered. /// Note: first initialize the Scanner. ///</summary> public static int Parse(string/*!*/ s, string/*!*/ fullFilename, string/*!*/ filename, ModuleDecl module, BuiltIns builtIns, ErrorReporter reporter, bool verifyThisFile=true) { Contract.Requires(s != null); Contract.Requires(filename != null); Contract.Requires(module != null); Errors errors = new Errors(reporter); return Parse(s, fullFilename, filename, module, builtIns, errors, verifyThisFile); }
/* throws System.IO.IOException */ ///<summary> /// Parses top-level things (modules, classes, datatypes, class members) from "filename" /// and appends them in appropriate form to "module". /// Returns the number of parsing errors encountered. /// Note: first initialize the Scanner. ///</summary> public static int Parse(string/*!*/ filename, ModuleDecl module, BuiltIns builtIns, Errors/*!*/ errors, bool verifyThisFile=true) { Contract.Requires(filename != null); Contract.Requires(module != null); string s; if (filename == "stdin.dfy") { s = Microsoft.Boogie.ParserHelper.Fill(System.Console.In, new List<string>()); return Parse(s, filename, filename, module, builtIns, errors, verifyThisFile); } else { using (System.IO.StreamReader reader = new System.IO.StreamReader(filename)) { s = Microsoft.Boogie.ParserHelper.Fill(reader, new List<string>()); return Parse(s, filename, DafnyOptions.Clo.UseBaseNameForFileName ? Path.GetFileName(filename) : filename, module, builtIns, errors, verifyThisFile); } } }
FunctionSymbol CreateFunctionDef(BuiltIns.FuncShape fn) { IType returnType = ConvertTypeAndNullable(fn.ReturnType); List<IType> formalTypes = fn.FormalTypes.ConvertAll(desc => ConvertTypeAndNullable(desc)); // FunctionSymbol symFunctionDef = new FunctionSymbol(fn.Name, returnType, this.builtins); NadirAST nodeFunctionDef = new NadirAST(NadirParser.FunctionDef); NadirAST nodeReturnType = CreateBuiltinTypeNode(returnType); NadirAST nodeFormalParams = new NadirAST(NadirParser.FormalParams); NadirAST nodeOptions = new NadirAST(NadirParser.Options); // nodeFunctionDef.AddChild(CreateNameNode(fn.Name)); // 0 nodeFunctionDef.AddChild(nodeReturnType); // 1 nodeFunctionDef.AddChild(nodeFormalParams); // 2 nodeFunctionDef.AddChild(new NadirAST(NadirParser.Statements)); // 3 nodeFunctionDef.AddChild(nodeOptions); // 4 // for (int i = 0; i < fn.FormalNames.Count; i++) { NadirAST nodeFormalParam = new NadirAST(NadirParser.FormalParam); NadirAST nodeName = CreateNameNode(fn.FormalNames[i]); NadirAST nodeType = CreateBuiltinTypeNode(formalTypes[i]); NadirAST nodeFormalOptions = new NadirAST(NadirParser.Options); nodeFormalParam.AddChild(nodeName); nodeFormalParam.AddChild(nodeType); nodeFormalParam.AddChild(nodeFormalOptions); // if (fn.FormalTypes[i].IsRef) nodeFormalOptions.AddChild(new NadirAST(NadirParser.Ref)); if (fn.FormalTypes[i].IsOut) nodeFormalOptions.AddChild(new NadirAST(NadirParser.Out)); if (i==0 && fn.IsMethod) nodeFormalOptions.AddChild(new NadirAST(NadirParser.This)); // NadirASTDefineSymbols.LinkSymbolWithDefinition(nodeFormalParam, new VariableSymbol(fn.FormalNames[i], false, null)); NadirASTDefineTypes.SetResolvedTypeOfDefinition(nodeFormalParam, formalTypes[i]); // Debug.Assert(FormalParameter.FormalParamName(nodeFormalParam)==nodeName); Debug.Assert(FormalParameter.FormalParamType(nodeFormalParam)==nodeType); // nodeFormalParams.AddChild(nodeFormalParam); } // if (fn.IsVariadic) nodeOptions.AddChild(new NadirAST(NadirParser.Variadic)); if (fn.IsHoldFirst) nodeOptions.AddChild(new NadirAST(NadirParser.HoldFirst)); if (fn.IsHoldRest) nodeOptions.AddChild(new NadirAST(NadirParser.HoldRest)); if (fn.IsHoldAll) nodeOptions.AddChild(new NadirAST(NadirParser.HoldAll)); // NadirASTDefineSymbols.LinkSymbolWithDefinition(nodeFunctionDef, symFunctionDef); NadirASTDefineTypes.SetResolvedTypeOfDefinition(nodeFunctionDef, returnType); // symFunctionDef.NoteOptions(); // return symFunctionDef; }
IType ConvertTypeAndNullable(BuiltIns.FormalParamDesc t) { IType result; switch (t.Type) { case Constants.TYPE.Float: result = this.FloatType; break; case Constants.TYPE.Integer: result = this.IntegerType; break; case Constants.TYPE.Bool: result = this.BoolType; break; case Constants.TYPE.Mixture: result = this.MixtureType; break; case Constants.TYPE.Plex: result = this.PlexType; break; case Constants.TYPE.Strand: result = this.StrandType; break; case Constants.TYPE.Domain: result = this.DomainType; break; case Constants.TYPE.Void: result = this.VoidType; break; case Constants.TYPE.Object: result = this.ObjectType; break; case Constants.TYPE.String: result = this.StringType; break; case Constants.TYPE.Melt: result = this.MeltType; break; case Constants.TYPE.SeqDesignObject: result = this.SeqDesignType; break; case Constants.TYPE.GenericType0: result = new GenericParameterType(0); break; case Constants.TYPE.List: result = new ListTypeSymbol(this); break; case Constants.TYPE.ListOfString: result = new ListTypeSymbol(this, this.StringType); break; default: throw new InternalErrorException("missing type in TypeFromEnum"); } // return result; }