Skip to content
This repository
Fetching contributors…

Cannot retrieve contributors at this time

file 370 lines (330 sloc) 12.862 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370
/*
* Copyright (c) 2003-2008 The University of Wroclaw.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the University may not be used to endorse or promote
* products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE UNIVERSITY ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
* NO EVENT SHALL THE UNIVERSITY BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

using StringTemplate;

using Nemerle;
using Nemerle.Compiler;
using Nemerle.Collections;
using Nemerle.Utility;
using Nemerle.Compiler.Parsetree;

using System;
using System.Diagnostics.Debug;
using System.Reflection;
using System.Text;

using TT = Nemerle.Compiler.Typedtree;
using TExpr = Nemerle.Compiler.Typedtree.TExpr;
using PT = Nemerle.Compiler.Parsetree;
using BF = System.Reflection.BindingFlags;
using SCG = System.Collections.Generic;

namespace Nemerle.IO
{
  using Nemerle.IO.Helper;
  
  macro printf (format, params parms : array [expr])
  {
    PrintfHelper(format, Macros.ImplicitCTX().Env, fun (strFormat) {
      def (evals, refs) = make_evaluation_exprs (parse_format (strFormat), parms);
      def seq = evals + refs.Map(x => <[ Console.Write ($x) ]>);
      <[ { .. $seq } ]>
    })
  }

  macro sprintf (format, params parms : array [expr])
  {
    when (parms.Length == 0)
      Message.Warning ("sprintf with no parameters");

    PrintfHelper(format, Macros.ImplicitCTX().Env, fun (strFormat) {
      def format = parse_format (strFormat);
      def (evals, refs) = make_evaluation_exprs (format, parms);
      def exprs = match (refs)
      {
          | [] => Message.Warning ("empty format"); [<[ "" ]>]
        | [expr] =>
          if (format.Head.NeedsNullCheck)
            evals + [<[ if ($expr == null) string.Empty else $expr.ToString () ]>]
          else
            evals + [<[ $expr.ToString () ]>]
        | _ :: _ => evals + [<[ string.Concat (..$refs) ]>]
      }
      <[ { ..$exprs } ]>
    })
  }

  /** Writes output to given System.IO.TextWriter */
  macro fprintf (writer, format, params parms : array [expr])
  {
    PrintfHelper(format, Macros.ImplicitCTX().Env, fun (strFormat) {
      def (evals, refs) = make_evaluation_exprs (parse_format (strFormat), parms);
      def seq = evals + refs.Map(x => <[ writer_v.Write ($x) ]>);
      <[
def writer_v = $writer : IO.TextWriter;
        {.. $seq }
      ]>
    })
  }

  macro scanf (format : string, params parms : array [expr])
  {
    def res = make_scan_expressions (format, parms, <[ stdin ]>);
    <[
def stdin = Console.In;
      $res
    ]>
  }

  macro fscanf (stream, format : string, params parms : array [expr])
  {
    def res = make_scan_expressions (format, parms, <[ stream_cached ]>);
    <[
def stream_cached = $stream;
      $res
    ]>
  }

  macro sscanf (str, format : string, params parms : array [expr])
  {
    def res = make_scan_expressions (format, parms, <[ stream_cached ]>);
    <[
def stream_cached = IO.StringReader ($str);
      $res
    ]>
  }

  macro sprint(str)
  {
    StringTemplate.Helper.SprintImpl(str, true, expr => expr, Macros.ImplicitCTX().Env)
  }

  // use writer.Write($"...") instade
  // macro fprint (writer, str : string)
  // {
  // <[ $writer.Write(sprint($(str : string))) ]>
  // }


  /// If string literal is supplied, then prints it to System.Console, replacing all
  /// occurences of $id with id.ToString () invocation
  /// If any other expression is supplied, it is equivalent to System.Console.Write
  macro print (value)
  {
    match (value)
    {
      | <[ $(_ : string) ]> => StringTemplate.Helper.SprintImpl(
                                   value, false, expr => <[ Console.Write($expr) ]>, Macros.ImplicitCTX().Env)
      | _ => <[ Console.Write ($value) ]>
    }
  }

  // module internal to this assembly used for compile time analysis of string formatters, etc.
  internal module Helper
  {
    public PrintfHelper(format : PExpr, env : GlobalEnv, makeExpr : string -> PExpr) : PExpr
    {
      match (ConstantFolder.FoldConstants(env, format))
      {
        | PExpr.Literal(Literal.String(strFormat)) => makeExpr(strFormat)
        | _ => Message.Error ("The 'format' parameter mast be string literal.");
               PExpr.Error ()
      }
    }

    public variant FormatToken {
      | Text { body : string; }
      | Number { unsigned : bool; longformat : bool; }
      | NumberFloat { longformat : bool; }
      | Str
      | Chr
      | WhiteSpace
      
      public NeedsNullCheck : bool {
        get {
          match (this) {
            | Text | Str => true
            | Number | NumberFloat | Chr | WhiteSpace => false
          }
        }
      }
    }

    /// parse printf-style formatting string
    /// http://www.gnu.org/software/libc/manual/html_node/Formatted-Output.html#Formatted%20Output
    public parse_format (form : string, scan : bool = false) : list [FormatToken]
    {
      def buf = StringBuilder ();
      mutable result = [];
      mutable i = 0;
      def n = form.Length;
  /*
def parse_percent () : FormatToken {
match (form [i]) {
|

}
}
*/
      def append_text ()
      {
        match (result) {
          | FormatToken.Text (t) :: rest =>
              result = FormatToken.Text (t + buf.ToString ()) :: rest
          | _ =>
              result = FormatToken.Text (buf.ToString ()) :: result
        }
        ignore (buf.Remove (0, buf.Length));
      }

      while (i < n)
      {
        match (form[i])
        {
          | '%' =>
            // % occured - first, dump text from buffer
            when ( buf.Length > 0 ) append_text ();

            mutable longform = false;

            def next_char () {
              // now analyze next character
              ++i;

              if ( i < n ) {
                match (form[i]) {
                  | 'd' | 'i' => result = FormatToken.Number (false, longform) :: result
                  | 'u' => result = FormatToken.Number (true, longform) :: result
                  | 'f' => result = FormatToken.NumberFloat (longform) :: result
                  | 's' => result = FormatToken.Str () :: result
                  | 'c' => result = FormatToken.Chr () :: result
                  | '%' => ignore (buf.Append ('%'))
                  | 'l' =>
                    if (longform)
                      Message.Error ("`l' in printf-format specified twice")
                    else {
                      longform = true; next_char ();
                    }
                  | _ =>
                    Message.Error ("Unsupported formatting sequence after % character")
                }
              }
              else
                Message.Error ("Unexpected end of format after % character")
            }
            next_char ();

          | c when scan && Char.IsWhiteSpace (c) => result = FormatToken.WhiteSpace () :: result
          | c => ignore (buf.Append (c))
        }
        
        ++i;
      }

      when (buf.Length > 0) append_text ();

      // the result is reversed, but function using it will reverse it again
      result
    }

    public make_evaluation_exprs (toks : list [FormatToken], parms : array [PT.PExpr])
    : list [PT.PExpr] * list [PT.PExpr]
    {
      def make_expressions (toks, i, acc_eval, acc_ref)
      {
        def continue (x, xs) {
          def sym = Macros.NewSymbol ();
          make_expressions (xs, i - 1, <[ def $(sym : name) = $x ]> :: acc_eval,
                            <[ $(sym : name) ]> :: acc_ref)
        }

        match (toks) {
          | [] when i == 0 => (acc_eval, acc_ref)
          | FormatToken.Text (t) :: xs =>
            make_expressions (xs, i, acc_eval, <[ $(t : string) ]> :: acc_ref)

          | _ when i == 0 =>
            Message.Error ("not enough arguments for printf macro");
            (acc_eval, acc_ref)

          | FormatToken.Number (false, false) :: xs => continue (<[ $(parms[i - 1]) : int ]>, xs)
          | FormatToken.Number (true, false) :: xs => continue (<[ $(parms[i - 1]) : uint ]>, xs)
          | FormatToken.Number (false, true) :: xs => continue (<[ $(parms[i - 1]) : long ]>, xs)
          | FormatToken.Number (true, true) :: xs => continue (<[ $(parms[i - 1]) : ulong ]>, xs)

          | FormatToken.NumberFloat (false) :: xs =>
            continue (<[ Convert.ToString (($(parms[i - 1]) : float),
                           Globalization.NumberFormatInfo.InvariantInfo) ]>, xs)
          | FormatToken.NumberFloat (true) :: xs =>
            continue (<[ Convert.ToString (($(parms[i - 1]) : double),
                           Globalization.NumberFormatInfo.InvariantInfo) ]>, xs)

          | FormatToken.Str :: xs => continue (<[ $(parms[i - 1]) : string ]>, xs)
          | FormatToken.Chr :: xs => continue (<[ $(parms[i - 1]) : char ]>, xs)

          | [] =>
            Message.Error ("too many arguments for printf macro");
            (acc_eval, acc_ref)

          | FormatToken.WhiteSpace :: _ => assert(false)
        }
      }

      make_expressions (toks, parms.Length, [], []);
    }

    public make_scan_results (format : string, stream : PT.PExpr) : list[PT.PExpr] * PT.PExpr {
      def format = parse_format (format).Rev ();
      def eat_space = <[ ConsumeWhiteSpace ($stream) ]>;
      def (read, res) = format.FoldLeft (([], []), fun (fmt, (acc_read, res)) {
        match (fmt : FormatToken) {
          | Text (t) =>
            (<[ CheckInput ($(t : string), $stream) ]> :: acc_read, res)
          | WhiteSpace =>
            (eat_space :: acc_read, res)
          | Number (usig, lng) =>
            def acc_read = acc_read.Rev ();
            def conv = match ((usig, lng)) {
              | (false, false) => <[ Convert.ToInt32 ]>
              | (false, true) => <[ Convert.ToInt64 ]>
              | (true, false) => <[ Convert.ToUInt32 ]>
              | (true, true) => <[ Convert.ToUInt64 ]>
            }
            ([], <[ { ..$acc_read }; $eat_space; $conv (ReadIntDigits ($stream)) ]> :: res)
          | Str =>
            def acc_read = acc_read.Rev ();
            ([], <[
{ ..$acc_read };
              $eat_space;
              def res = ReadString ($stream);
              when (res.Length == 0)
                throw Nemerle.IO.InvalidInput ();
              res
            ]> :: res)
          | Chr =>
            def acc_read = acc_read.Rev ();
            ([], <[ { ..$acc_read }; Convert.ToChar ($stream.Read ()) ]> :: res)
          | NumberFloat =>
            Message.FatalError ("scaning floats not supported")
        }
      });
      (res.Rev (), <[ {..$(read.Rev ())} ]>)
    }

    public make_scan_expressions (format : string, parms : array [PT.PExpr],
                           stream : PT.PExpr) : PT.PExpr {
      def (lst, read) = make_scan_results (format, stream);
      def lstLen = lst.Length;
      if (parms.Length == 0 && lstLen > 0) { // return tuple of results
        def res = Macros.NewSymbol ();
        def lst = match (lst) {
          | [e] => e
          | _ => <[ (..$lst) ]>
        }
        <[
def $(res : name) = $lst;
          $read;
          $(res : name);
        ]>
      } else if (parms.Length < lstLen) {
        Message.Error ("not enough arguments for scanf-style macro");
        <[ () ]>
      } else if (parms.Length > lstLen) {
        Message.Error ("too many arguments for scanf macro");
        <[ () ]>
      } else {
        def (lst, _) = lst.FoldLeft (([], 0), fun (e, (acc, i)) {
          (<[ $(parms[i]) = $e ]> :: acc, i + 1)
        });
        def lst = lst.Rev ();
        <[ { ..$lst }; $read ]>
      }
    }
  }
}
Something went wrong with that request. Please try again.