Package loop.ast.script

Examples of loop.ast.script.FunctionDecl


    for (Node expr : exprs) {
      Variable argName = (Variable) expr;
      args.add(new ArgDeclList.Argument(argName.name, null));
    }

    FunctionDecl functionDecl = new FunctionDecl(name, args);

    Node fourth = list.children().get(3);
    functionDecl.children().add(reduceNode(fourth));
    return functionDecl;
  }
View Full Code Here


        unit.declare(require);
      }
    } while (require != null);

    FunctionDecl function;
    ClassDecl classDecl = null;
    do {
      function = functionDecl();
      if (function == null) {
        classDecl = classDecl();
      }

      chewEols();

      if (null != function) {
        if (unit.resolveFunction(function.name(), false) != null) {
          addError("Duplicate function definition: " + function.name(),
              function.sourceLine,
              function.sourceColumn);
          throw new LoopCompileException();
        }
View Full Code Here

    }

    ArgDeclList arguments = argDeclList();
    String name = anonymous ? null : funcName.get(0).value;
    startTokens = funcName != null ? funcName : startTokens;
    FunctionDecl functionDecl = new FunctionDecl(name, arguments).sourceLocation(startTokens);

    // We need to set the module name here because closures are not declared as
    // top level functions in the module.
    if (anonymous)
      functionDecl.setModule(scope.getModuleName());

    // Before we match the start of the function, allow for cell declaration.
    List<Token> inCellTokens = match(Kind.IN, Kind.PRIVATE_FIELD);
    if (inCellTokens != null) {
      functionDecl.cell = inCellTokens.get(1).value;
    }

    // Before we match the arrow and start the function, slurp up any exception handling logic.
    List<Token> exceptHandlerTokens = match(Kind.IDENT, Kind.IDENT);
    if (exceptHandlerTokens == null)
      exceptHandlerTokens = match(Kind.IDENT, Kind.PRIVATE_FIELD);

    if (exceptHandlerTokens != null) {
      Token exceptToken = exceptHandlerTokens.get(0);
      if (!RestrictedKeywords.EXCEPT.equals(exceptToken.value)) {
        addError("Expected 'expect' keyword after function signature", exceptToken);
      }
      functionDecl.exceptionHandler = exceptHandlerTokens.get(1).value;
    }

    // If it doesn't have a thin or fat arrow, then it's not a function either.
    if (match(Token.Kind.ARROW, Token.Kind.LBRACE) == null) {
      // Fat arrow, pattern matcher.
      if (match(Token.Kind.HASHROCKET, Token.Kind.LBRACE) == null) {
        return null;
      } else
        return patternMatchingFunctionDecl(functionDecl);
    }

    // Optionally match eols here.
    chewEols();

    Node line;

    // Absorb indentation level.
    withIndent();

    boolean hasBody = false;
    while ((line = line()) != null) {
      hasBody = true;
      functionDecl.add(line);

      // Multiple lines are allowed if terminated by a comma.
      if (match(Kind.EOL) == null)
        break;
View Full Code Here

  private boolean whereBlock(FunctionDecl functionDecl) {
    withIndent();
    boolean hasWhere = false;
    if (match(Token.Kind.WHERE) != null) {
      FunctionDecl helperFunction = null;
      Node assignment;
      do {
        chewEols();
        withIndent();
View Full Code Here

  static void compareFunction(String functionName, String expected, String input) {
    Parser parser = new LexprParser(new Tokenizer(input).tokenize());
    Unit unit = parser.script(null);
    Assert.assertNotNull("Parser returned no output", unit);

    FunctionDecl function = unit.resolveFunction(functionName, false);
    Assert.assertNotNull("No such function " + functionName, function);


    String stringified = LexprParser.stringify(function);
View Full Code Here

        }
    }
  }

  public Object main(String[] commandLine) {
    FunctionDecl main = scope.resolveFunction("main", false);
    if (main != null) {
      int args = main.arguments().children().size();
      if(commandLine == null)
        commandLine = new String[] {};
      try {
        if (args == 0)
          return compiled.getDeclaredMethod("main").invoke(null);
View Full Code Here

    this.scope = scope;
    List<Token> tokens = new Tokenizer(source).tokenize();
    Parser parser = isLisp
        ? new SexprParser(tokens)
        : new LexprParser(tokens);
    FunctionDecl functionDecl = parser.functionDecl();
    ClassDecl classDecl = null;
    Node node;
    if (null == functionDecl) {
      classDecl = parser.classDecl();
      node = classDecl;
View Full Code Here

    try {
      reader.setExpandEvents(false);
      reader.addCompleter(new MetaCommandCompleter());

      Unit shellScope = new Unit(null, ModuleDecl.SHELL);
      FunctionDecl main = new FunctionDecl("main", null);
      shellScope.declare(main);
      shellContext = new HashMap<String, Object>();

      boolean inFunction = false;

      // Used to build up multiline statement blocks (like functions)
      StringBuilder block = null;
      //noinspection InfiniteLoopStatement
      do {
        String prompt = (block != null) ? "|    " : ">> ";
        String rawLine = reader.readLine(prompt);

        if (inFunction) {
          if (rawLine == null || rawLine.trim().isEmpty()) {
            inFunction = false;

            // Eval the function to verify it.
            printResult(Loop.evalClassOrFunction(block.toString(), shellScope));
            block = null;
            continue;
          }

          block.append(rawLine).append('\n');
          continue;
        }

        if (rawLine == null) {
          quit(reader);
        }

        //noinspection ConstantConditions
        String line = rawLine.trim();
        if (line.isEmpty())
          continue;

        // Add a require import.
        if (line.startsWith("require ")) {
          shellScope.declare(new LexprParser(new Tokenizer(line + '\n').tokenize()).require());
          shellScope.loadDeps("<shell>");
          continue;
        }

        if (line.startsWith(":q") || line.startsWith(":quit")) {
          quit(reader);
        }

        if (line.startsWith(":h") || line.startsWith(":help")) {
          printHelp();
        }

        if (line.startsWith(":run")) {
          String[] split = line.split("[ ]+", 2);
          if (split.length < 2 || !split[1].endsWith(".loop"))
            System.out.println("You must specify a .loop file to run.");
          Loop.run(split[1]);
          continue;
        }

        if (line.startsWith(":r") || line.startsWith(":reset")) {
          System.out.println("Context reset.");
          shellScope = new Unit(null, ModuleDecl.SHELL);
          main = new FunctionDecl("main", null);
          shellScope.declare(main);
          shellContext = new HashMap<String, Object>();
          continue;
        }
        if (line.startsWith(":i") || line.startsWith(":imports")) {
          for (RequireDecl requireDecl : shellScope.imports()) {
            System.out.println(requireDecl.toSymbol());
          }
          System.out.println();
          continue;
        }
        if (line.startsWith(":f") || line.startsWith(":functions")) {
          for (FunctionDecl functionDecl : shellScope.functions()) {
            StringBuilder args = new StringBuilder();
            List<Node> children = functionDecl.arguments().children();
            for (int i = 0, childrenSize = children.size(); i < childrenSize; i++) {
              Node arg = children.get(i);
              args.append(arg.toSymbol());

              if (i < childrenSize - 1)
                args.append(", ");
            }

            System.out.println(functionDecl.name()
                + ": (" + args.toString() + ")"
                + (functionDecl.patternMatching ? " #pattern-matching" : "")
            );
          }
          System.out.println();
          continue;
        }
        if (line.startsWith(":t") || line.startsWith(":type")) {
          String[] split = line.split("[ ]+", 2);
          if (split.length <= 1) {
            System.out.println("Give me an expression to determine the type for.\n");
            continue;
          }

          Object result = evalInFunction(split[1], main, shellScope, false);
          printTypeOf(result);
          continue;
        }

        if (line.startsWith(":javatype")) {
          String[] split = line.split("[ ]+", 2);
          if (split.length <= 1) {
            System.out.println("Give me an expression to determine the type for.\n");
            continue;
          }

          Object result = evalInFunction(split[1], main, shellScope, false);
          if (result instanceof LoopError)
            System.out.println(result.toString());
          else
            System.out.println(result == null ? "null" : result.getClass().getName());
          continue;
        }

        // Function definitions can be multiline.
        if (line.endsWith("->") || line.endsWith("=>")) {
          inFunction = true;
          block = new StringBuilder(line).append('\n');
          continue;
        } else if (isDangling(line)) {
          if (block == null)
            block = new StringBuilder();

          block.append(line).append('\n');
          continue;
        }

        if (block != null) {
          rawLine = block.append(line).toString();
          block = null;
        }

        // First determine what kind of expression this is.
        main.children().clear();

        // OK execute expression.
        try {
          printResult(evalInFunction(rawLine, main, shellScope, true));
        } catch (ClassCastException e) {
View Full Code Here

    functionStack.pop();
  }

  private void verifyExceptionHandler(FunctionDecl functionDecl) {
    FunctionDecl exceptionHandler = resolveCall(functionDecl.exceptionHandler);
    if (exceptionHandler == null)
      addError("Cannot resolve exception handler: " + functionDecl.exceptionHandler,
          functionDecl.sourceLine, functionDecl.sourceColumn);
    else {
      int argsSize = exceptionHandler.arguments().children().size();
      // Verify exception handler template.
      if (!exceptionHandler.patternMatching)
        addError("Exception handler must be a pattern-matching function (did you mean '=>')",
            exceptionHandler.sourceLine, exceptionHandler.sourceColumn);
      else if (argsSize != 1) {
        addError("Exception handler must take exactly 1 argument (this one takes "
            + argsSize + ")", exceptionHandler.sourceLine, exceptionHandler.sourceColumn);
      } else {
        for (Node child : exceptionHandler.children()) {
          PatternRule rule = (PatternRule) child;

          // Should have only 1 arg pattern.
          Node patternNode = rule.patterns.get(0);
          if (patternNode instanceof PrivateField) {
View Full Code Here

      if (call.isJavaStatic() || call.isPostfix())
        return;

      verifyNode(call.args());

      FunctionDecl targetFunction = resolveCall(call.name);
      if (targetFunction == null)
        addError("Cannot resolve function: " + call.name, call.sourceLine, call.sourceColumn);
      else {
        // Check that the args are correct.
        int targetArgs = targetFunction.arguments().children().size();
        int calledArgs = call.args().children().size();
        if (calledArgs != targetArgs)
          addError("Incorrect number of arguments to: " + targetFunction.name()
              + " (expected " + targetArgs + ", found "
              + calledArgs + ")",
              call.sourceLine, call.sourceColumn);
      }

    } else if (node instanceof PatternRule) {
      PatternRule patternRule = (PatternRule) node;
      verifyNode(patternRule.rhs);

      // Some sanity checking of pattern rules.
      FunctionDecl function = functionStack.peek().function;
      int argsSize = function.arguments().children().size();
      int patternsSize = patternRule.patterns.size();
      if (patternsSize != argsSize)
        addError("Incorrect number of patterns in: '" + function.name() + "' (expected " + argsSize
            + " found " + patternsSize + ")", patternRule.sourceLine, patternRule.sourceColumn);

    } else if (node instanceof Guard) {
      Guard guard = (Guard) node;
      verifyNode(guard.expression);
View Full Code Here

TOP

Related Classes of loop.ast.script.FunctionDecl

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.